【问题标题】:Angular $cookies "Circular dependency found"Angular $cookies“找到​​循环依赖”
【发布时间】:2016-10-27 16:39:22
【问题描述】:

收到此错误“错误:[$injector:cdep] 找到循环依赖项:$cookies

以下代码

'use strict';

angular.
  module('core.auth').
  factory('AuthService', [ '$http', '$rootScope', 'ConfigService', '$cookies',
    function AuthService($http, $rootScope, ConfigService, $cookies) {
      const service = {};

      service.Login = Login;
      service.SetCredentials = SetCredentials;
      service.ClearCredentials = ClearCredentials;

      return service;

      function Login(username, password, callback) {
        $http.post(ConfigService.LOGIN_API, { username: username, password: password })
           .success(function (response) {
               callback(response);
           });
      }

      function SetCredentials(username) {
        $rootScope.globals = {
          currentUser: {
            username: username
          }
        };

        $cookies.put('globals', $rootScope.globals);
      }

      function ClearCredentials() {
        $rootScope.globals = {};
        $cookies.remove('globals');
      }
    }
]);

我在登录组件中使用此服务

'use strict';

angular.
  module('login').
  component('login', {
    templateUrl: 'dist/components/login/login.template.html',
    controller: ['$location', 'AuthService', '$log',
      function LoginController($location, AuthService, $log) {

      (function initController() {
          // reset login status
          AuthService.ClearCredentials();
        }());

        this.login = () => {
          AuthService.Login(this.username, this.password, (response) => {
            if (response.success) {
              $log.log(response);
              $log.log('Login successful', true);
              AuthService.SetCredentials(this.username);
              $location.path('#!/products');
            } else {
              $log.log(response)
            }
          })
        }

      }
    ],

    controllerAs: 'vm'
});

无法理解我的代码有什么问题...如果从这里删除 $cookies,它工作得很好。也许解决方案是编写自己的 cookie 服务? :)

【问题讨论】:

  • 在不查看其他服务的情况下很难诊断您的问题。如果您花时间在 Plnkr 中隔离您的问题,网站上的某个人可能会帮助您找出问题。
  • 也许我使用了错误的工具。我解决了刚刚替换 ngCookies -> ngStorage 的问题。工作正常:)

标签: angularjs cookies circular-dependency angular-cookies


【解决方案1】:

循环依赖总是关注点混合的标志,这是一件非常糟糕的事情。AngularJS 的作者之一解释了一个很好的解决方案on his awesome blog。简而言之,您可能在某处隐藏了第三个服务,这是其他两个真正需要的代码中唯一的部分。

【讨论】:

    猜你喜欢
    • 2023-03-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多