angelokh
angelokh

Reputation: 9428

how to use cookiesProvider in angular config

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.config(["someProvider", "$cookiesProvider", function(someProvider, $cookiesProvider) {
    someProvider.set('configs', {'token': $cookiesProvider["XSRF-TOKEN"]})
  }]);

Upvotes: 17

Views: 18889

Answers (3)

Kamil Szot
Kamil Szot

Reputation: 17817

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

Upvotes: 30

VasylChepil
VasylChepil

Reputation: 21

Also you can write something like this:

$cookiesProvider.$get()["XSRF-TOKEN"]

Upvotes: 1

Betty St
Betty St

Reputation: 2870

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

Upvotes: 13

Related Questions