2

我是网络开发和 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')。但是,如果上面的代码是正确的,那可能是由于我的代码中的一些其他错误。提前谢谢...

4

1 回答 1

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');
}]);
于 2014-10-29T11:19:50.933 回答