在 angular js 中发现循环依赖

Circular dependency found in angular js

试图为我的每个请求添加拦截器 header,但是,它给我以下错误。

Uncaught Error: [$injector:cdep] Circular dependency found: $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. 您已经创建了 httpRequestInterceptor,它拦截了所有 $http 请求。

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

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

  4. 因此,您的 interceptor 本身可以使用 Auth.

  5. 引发 http 请求

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

Auth 工厂删除 $http 不要将服务插入本身使用 $http.

的拦截器

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