Setting and getting objects in cookies with Angular 1.2

820 views Asked by At

I'm trying to set user properties in cookies. On login, the following code is run:

$scope.$parent.session.user = response.data.user;

// Get profile information
$http.get('api/v1/profiles/' + response.data.user.id)
  .then(function(response){
    $scope.$parent.session.user.profile = response.data;
  });

// Set cookie data
console.log($scope.$parent.session.user);
$cookieStore.put('user', $scope.$parent.session.user);

The logged data includes the profile object, so I assume that this is placed into cookies too.

When the app is loaded, I look for cookies with:

if ($cookieStore.get('user')){
    $scope.session.user = $cookieStore.get('user');
  }

This returns just the user object, without the profile object. What am I doing wrong here?

1

There are 1 answers

0
wvdz On BEST ANSWER

It's weird that you say it is logged correctly, but it still looks like a synchronity issue. You should set the cookie in the body of the $http callback..

$http.get('api/v1/profiles/' + response.data.user.id)
  .then(function(response){
    $scope.$parent.session.user.profile = response.data;
    $cookieStore.put('user', $scope.$parent.session.user);
  });