繁体   English   中英

在angular js中发现循环依赖

[英]Circular dependency found in angular js

试图为我的每个请求添加拦截器标头,但是,这给了我下面的错误。

未捕获的错误:[$ injector:cdep]找到循环依赖项:$ http <-Auth <-httpRequestInterceptor <-$ http <-$ templateRequest <-$ route

app.js

var app= angular.module('myDemoApp',['ngRoute'])


app.factory('httpRequestInterceptor', ['Auth', function (Auth) {
  return {
    request: function (config) {

      config.headers['x-access-token'] = Auth.getToken();
      return config;
    }
  };
}]);

app.config(function ($httpProvider) {
  $httpProvider.interceptors.push('httpRequestInterceptor');
});

验证服务

(function () {
    'use strict';

    myDemoApp.factory('Auth', ['$http', '$window', Auth]);

    /******Auth function start*****/
    function Auth($http, $window) {
        var authFactory = {};

        authFactory.setToken = setToken;
        authFactory.getToken = getToken;
        return authFactory;


        /*setToken function start*/
        function setToken(token) {

            if (token) {
                $window.localStorage.setItem('token', token);
            } else {
                $window.localStorage.removeItem('token');
            }

        }

        /*getToken function start*/
        function getToken() {
            return $window.localStorage.getItem('token')
        }

    }


})();

您不能这样做,因为。

  1. 您已经创建了拦截所有$http请求的httpRequestInterceptor

  2. 现在,您正在httpRequestInterceptor中传递Auth

  3. 如果看到的话, Auth会在自己内部使用$http请求。

  4. 因此,您的interceptor器本身可以使用Auth引发http请求。

因此,它的循环错误和angularjs不允许您这样做!

Auth工厂中删除$http或者不要将服务插入本身使用$http拦截器中。

希望您知道如何创建无限循环链,从而导致circular dependency错误!

暂无
暂无

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

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