angular:如何在截获的响应头中设置cookie?

时间:2014-10-29 10:20:03

标签: angularjs cookies angular-cookies

我是web-deveopment和angularJS的新手。我知道如何使用角度拦截器拦截响应。我现在想要为此响应添加cookie,稍后可以使用$cookieStore.get('DEMO_COOKIE')访问..我该怎么做?基本上我想知道以下代码补丁:

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');
    }]);

使用当前代码,我得到$cookieStore.get('DEMO_COOKIE')的未定义值。但是,如果上面的代码是正确的,可能是由于我的代码中的其他一些错误。提前谢谢......

1 个答案:

答案 0 :(得分:0)

您可以通过向拦截器注入$cookieStore来执行此操作。然后,您可以使用$cookieStore.put()方法添加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');
}]);