Angular 'Error: $injector:cdep Circular Dependency' when using factory in app.js

Angular 'Error: $injector:cdep Circular Dependency' when using factory in app.js

我正在尝试使用令牌来处理我的用户身份验证。我在路上遇到了一个颠簸,我不完全确定从这里去哪里。我环顾四周,看起来我应该使用 $injector 服务,但我不是 100% 确定。有人可以帮忙吗?

我创建了一个从节点获取令牌的工厂:

angular.module('myApp').factory('authenticateInterceptor', function(authenticateToken){

var authenticateInterceptorFactory = {};

authenticateInterceptorFactory.request = function(config){

    var token = authenticateToken.getToken();

    if(token){
        config.headers['x-access-token'] = token;
    };

    return config;
}

return authenticateInterceptorFactory;

});

这是 autenticateToken 的代码:

angular.module('myApp').factory('authenticateToken', function($http, $window){

    authenticateTokenFactory = {};

    authenticateTokenFactory.getToken = function(token){
        return $window.localStorage.getItem('token');
    };

    return authenticateTokenFactory;

});

这里没有错误,当我尝试在我的 app.js.

中使用这个工厂时,问题就来了
angular.module('myApp', [
    'dependancies goes here'
])
.config(function($httpProvider){
    $httpProvider.interceptors.push('authenticateInterceptor');
});

这会导致错误,我似乎无法将我的工厂传递给拦截器。

循环依赖很可能是由 $http 服务注入 authenticateToken 工厂

引起的

存在冲突是因为在 angular 尝试按此顺序解决 $http 依赖项(以及其他核心服务)。

  1. $httpProvider 依赖关系
  2. authenticateInterceptor 依赖关系
  3. authenticateToken依赖项(包括$http,这里我们回到1.)

顺便说一句,由于 $http 服务未在 authenticationFactory 中使用,您甚至可以删除注入,但如果您需要该服务,您可以尝试动态注入它,只是需要避免这种行为。

angular.module('myApp').factory('authenticateToken', function($injector, $window){

    authenticateTokenFactory = {};

    authenticateTokenFactory.getToken = function(token){
        return $window.localStorage.getItem('token');
    };

   authenticateTokenFactory.otherMethod = function(){
    //this code is not reached when your interceptor is added to 
    //$httpProvider interceptors array so theorically neither the exception
     var http = $injector.get('$http');
     http.get (/)...

   }

    return authenticateTokenFactory;

});