17

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"]})
  }]);
Community
  • 1
  • 1
angelokh
  • 9,426
  • 9
  • 69
  • 139

3 Answers3

30

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
});
Kamil Szot
  • 17,436
  • 6
  • 62
  • 65
13

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

Betty St
  • 2,741
  • 21
  • 33
  • `Run blocks typically contain code which is hard to unit-test, and for this reason should be declared in isolated modules, so that they can be ignored in the unit-tests.` -> From AngularJS docs, just an additional info... – Juan Biscaia Sep 30 '14 at 13:07
  • @JuanHBiscaia you are right, the right way would be to write an interceptor like here: https://gist.github.com/lpsBetty/76df8d1f037db87f4a0b I will update my answer – Betty St Oct 30 '14 at 14:35
1

Also you can write something like this:

$cookiesProvider.$get()["XSRF-TOKEN"]
Hans Z.
  • 50,496
  • 12
  • 102
  • 115
  • 1
    This causes `Uncaught Error: [$injector:modulerr] Failed to instantiate module x due to: TypeError: $cookiesProvider.$get is not a function`, although console logs that $cookiesProvider has $get at that moment – JustAMartin Sep 12 '17 at 20:32