角度$cookies "Circular dependency found"



得到此错误" error: [$injector:cdep] Circular dependencies found: $cookies <- $cookies <- AuthService"

带有以下代码

'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服务?:)

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

最新更新