简体   繁体   English

如何在Angular JS的工厂/服务中使用$ cookie?

[英]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(...)). 在我正在构建的应用程序之一中,我想在service(.factory(...))中使用$ cookie。

When i use the $cookie i get $injector/module error. 当我使用$ cookie时,出现$ injector / module错误。 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. 'clientId'是模块知道服务所依据的名称,而传递给工厂函数的参数是工厂所知道的名称。 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?" 该$ injector错误通常等于“您在谈论什么服务?”

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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