Bruno Camarneiro
Bruno Camarneiro

Reputation: 555

Is it possible to access $cookieStore from a service in angularjs?

I'm trying to access $cookieStore ($cookieStore.get("username")) from inside a service like this:

var angServices = angular.module('angServices', ['ngResource', 'ngCookies']);
angServices.factory('rsrUser', [ '$resource',
  function($resource, $cookieStore){
    var req = "/login"
    var timestamp = getMicrotime(true).toString();
    var username = $cookieStore.get("username");
    return $resource(baseURL + req, {}, {
      logIn: {method:'POST',
              isArray:false,
              headers:{
                  'X-MICROTIME': timestamp,
                  'X-USERNAME': username,
                  'X-HASH': getHMAC(timestamp, req)
                }
            }
    });
  }]);

But this returns TypeError: Cannot call method 'get' of undefined

Am I doing something wrong or there is a better why to achieve this?

Upvotes: 2

Views: 1779

Answers (2)

David Souther
David Souther

Reputation: 8184

You are using the annotated injections, but not supplying an annotation for the cookie store.

var angServices = angular.module('angServices', ['ngResource', 'ngCookies']);

// Add $cookieStore to the array,             here --\
angServices.factory('rsrUser', [ '$resource', '$cookieStore'

  function($resource, $cookieStore){
    // the same
  }
}]);

Upvotes: 5

Michael
Michael

Reputation: 3104

The arguments for the factory don't match your method signature. You need to add the '$cookieStore' to the parameter list or the second parameter will be undefined

angServices.factory('rsrUser', [ '$resource', '$cookieStore',

Upvotes: 1

Related Questions