Search code examples
angularjscookiesangular-cookies

angular: how to set cookies in intercepted response header?


I am new to web-deveopment and to angularJS. I know how to intercept a response using angular interceptors. I now want to add cookies to to this response, which can be later accessed using $cookieStore.get('DEMO_COOKIE')..How do I do it? Basically I want to know the following patch of code:

angular.module('APP').factory('myInterceptor', function() {
        return {
            response: function(response) {
                // code here for modifying incoming response by adding cookies to it 
                /*
                 Or Is this the right way to do it?
                 response.headers()['Set-Cookie']= 'DEMO_COOKIE=demo_session; expires=Sat, 18 Oct 2014 23:38:25 GMT; username=public; role=public';
                */
              return response
            }
        }
  })


   angular.module('APP').config(['$httpProvider', function($httpProvider) {
        $httpProvider.interceptors.push('myInterceptor');
    }]);

With the current code I get undefined value for $cookieStore.get('DEMO_COOKIE'). However if the above code is correct than that may be due to some other error in my code.Thanks in advance...


Solution

  • You can do this by injecting $cookieStore to your interceptor. Then you can use $cookieStore.put() method to add a cookie:

    angular.module('APP').factory('myInterceptor', ['$cookieStore', function ($cookieStore) {
        return {
            response: function (response) {
                $cookieStore.put('DEMO_COOKIE', 'I am a cookie!!!');
                return response;
            }
        };
    }]);
    
    
    angular.module('APP').config(['$httpProvider', function ($httpProvider) {
        $httpProvider.interceptors.push('myInterceptor');
    }]);