how to use cookiesProvider in angular config

前端 未结 3 396
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-04 00:53

I want get cookie value and set to a provider. This post https://stackoverflow.com/a/20415679/772481 mentioned $cookiesProvider. But how do I use it?

mod.con         


        
相关标签:
3条回答
  • 2021-01-04 01:11

    I wanted to set specific http headers on every http request, so this is my solution:

    I'm using the run function because in config I couldn't access cookies, see http://docs.angularjs.org/guide/module

    app.run(function run( $http, $cookies ){
      $http.defaults.headers.common["X-AUTH-TOKEN"] = $cookies['AUTH-TOKEN'];
    });
    

    If you don't want to use the run function for that configuration (because it's hard to unit-test), you can write an interceptor for the $httpProvider, similar to this: https://gist.github.com/lpsBetty/76df8d1f037db87f4a0b

    0 讨论(0)
  • 2021-01-04 01:12

    Also you can write something like this:

    $cookiesProvider.$get()["XSRF-TOKEN"]
    
    0 讨论(0)
  • 2021-01-04 01:18

    You can inject $cookies manually:

    myApp.config(function() {
      var $cookies;
      angular.injector(['ngCookies']).invoke(['$cookies', function(_$cookies_) {
        $cookies = _$cookies_;
      }]);
    
      // here you can use $cookies as usual
    });
    
    0 讨论(0)
提交回复
热议问题