简体   繁体   中英

How to use $cookie in factory/service in angular js?

In one of the app i am building, i want to use $cookie in service(.factory(...)).

When i use the $cookie i get $injector/module error. Can any one help me in this regard ?

Here is the code i have written.

app.factory("AuthenticationService", function($location,$cookies,setUserCreds) 
{

 return {

  login: function(credentials) {
    if (credentials.username == "MyName" || credentials.password == "admin") {
        $cookies.put("userName",credentials.username);          
        $location.path('/home');

   } 
}}});

This is the example from the angular documentation:

myApp.factory('apiToken', ['clientId', function apiTokenFactory(clientId) {
  var encrypt = function(data1, data2) {
    // NSA-proof encryption algorithm:
    return (data1 + ':' + data2).toUpperCase();
  };

  var secret = window.localStorage.getItem('myApp.secret');
  var apiToken = encrypt(clientId, secret);

  return apiToken;
}]);

'clientId' is the name the module knows the service by and the parameter you pass the factory function is the name your factory will know it by. You only have the parameter.

Yours should look like this:

app.factory("AuthenticationService",['$location', '$cookies', 'setUserCreds', function($location, $cookies, setUserCreds) {
    ...
}]);

That $injector error usually amounts to "What service are you talking about?"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM