Search code examples
angularjsangular-cookies

AngularJs - $cookies reflecting changes only after refresh on same state


I am using $cookies to store userId upon successful login from a modalInstanceController and then getting the userId in my homepageController. In the whole process the state of the app is not being changed and neither the page is reloaded. Now when I console log the userId during this process it shows undefined but when I refresh the page the userId is shown perfectly.

I am pre-filling the form on successful login, so I don't want to reload my state. Any solution for this so that I can achieve that.

Code Snippet :

modalInstanceController

 $scope.login = function() {
    utilities.login()
    .success(function(response) {
      $cookies.put('user_id', response.message.user_id);
    });
    $modalInstance.dismiss('cancel');
  };

homepageController

$scope.userId = $cookies.get('user_id');

userId is only shown upon page refresh.


Solution

  • There is no sign in your code that you are setting userId after receiving the information back from the server. The homepageController will only read the cookie when it is loaded

     $scope.login = function() {
        utilities.login()
        .success(function(response) {
          $cookies.put('user_id', response.message.user_id);
          // add next line
          $scope.userId = $cookies.get('user_id');
        });
        $modalInstance.dismiss('cancel');
     };