angularjscookiesangular-cookies

Angular $cookieStore not retaining updated cookie on refresh


I'm having issues with $cookieStore retaining a cookie value after updating it. Here are two methods of a UserService that deals with the cookie:

var getCurrentUser = function () {
    return $cookieStore.get('currentUser');
};

var updateCurrentUser = function () {
    return $http.get(baseUrl + 'api/session').then(function (response) {
        $cookieStore.put('currentUser', response.data);
        $rootScope.$broadcast('currentUser', response.data);
    }, function (response) {
        $cookieStore.remove('currentUser');
        $rootScope.$broadcast('currentUser', null);
    });
};

Throughout my app, after an action is executed that would affect the current user's meta data, I call UserService.updateCurrentUser() which retrieves the latest user data from the server and updates that cookie. Then, in places that display the user data, I have the following code that will update the user model in that particular controller:

$scope.$on('currentUser', function (event, data) {
    $scope.user = data;
});

As I step through the code, everything appears to be working correctly. After the $cookieStore.put('currentUser', response.data); line runs, the updated value can be confirmed by checking $cookieStore.get('currentUser'). When I check the actual cookie using a browser tool, however, the cookie value is not updated. I'm not sure if the browser tool requires a refresh to show the new data. But when I refresh the page, the updated cookie value is also no where to be seen. What is going on?

Thanks in advance.


Solution

  • Check out the documentation adding a cookie using $cookie service:

    put(key, value, [options]);
    

    The third argument allows additional options:

    You should set "expires" to define when the cookie should expire, otherwise the cookie will expire when you refresh or leave the site.

    $cookies.put("id", 1, {
        expires: new Date(2016, 1, 1)
    });
    

    Also the service is now called $cookies. Since Angular 1.4 you can now set expiry. Until then it wasn't possible.

    http://docs.angularjs.org/api/ngCookies/service/$cookies