【问题标题】:Circular dependency found in angular js在 Angular js 中发现循环依赖
【发布时间】:2019-08-11 22:45:38
【问题描述】:

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

未捕获的错误:[$injector:cdep] 找到循环依赖项:$http

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')
        }

    }


})();

【问题讨论】:

    标签: javascript angularjs angular-http-interceptors


    【解决方案1】:

    你不能这样做,因为。

    1. 您已创建httpRequestInterceptor,它拦截所有$http 请求。

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

    3. 如果您看到,Auth 在其内部使用 $http 请求。

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

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

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

    我希望你知道无限循环链是如何创建的,因此出现circular dependency 错误!

    【讨论】:

    • 谢谢。我已经删除了 $http 服务,它现在工作正常。
    猜你喜欢
    • 1970-01-01
    • 2023-03-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多