【问题标题】:Angular JS solve circular dependencyAngular JS 解决循环依赖
【发布时间】:2015-08-05 07:56:27
【问题描述】:

我尝试在 http 拦截器中执行 http.post 调用,但得到一个

Circular dependency found: $http <- Ace <- authInterceptor <- $http <- $templateRequest <- $compile

我明白了原因,但我不知道如何解决它... 仍然是 Angular 的新手,有时会有点困惑,我希望你能帮助我:) 这是我的代码:

var app = angular.module('AceAngularApi', []);

app.service('Ace', ['$http', '$q', '$injector', '$window', function($http, $q, $injector, $window) {

    var user = null;

    var getCurrentUser = function() {
        var url = "http://localhost:8080/api/currentuser";

        var response = $http.post(url, {}).then(function(response) {});
        return response;
    };
    return {
        getCurrentUser: getCurrentUser,
    }
}]);

app.factory('authInterceptor', ['$rootScope', '$q', '$window', '$injector', 'Ace',
    function($rootScope, $q, $window, $injector, Ace) {
        return {
            request: function(config) {
                config.headers = config.headers || {};
                if ($window.localStorage.token) {
                    config.headers.Authorization = 'Bearer ' + $window.sessionStorage.token;
                }
                return config;
            },
            response: function(response) {
                if (response.status === 401) {
                    // handle the case where the user is not authenticated
                } else {
                    Ace.getCurrentUser().then(function() {
                        console.log("Got current user");
                    });
                }
                return response || $q.when(response);
            }
        };
    }
]);

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

【问题讨论】:

  • authInterceptor 中使用var Ace = $injector.get('Ace'); 之类的注入器注入Ace 尝试一次

标签: javascript angularjs interceptor


【解决方案1】:

您试图通过将authInterceptor 注入$httpProvider 来定义$http 的预处理功能,但是authInterceptor 依赖于$http,这会导致循环依赖问题。

要解决此循环依赖问题,您可以使用$injector 服务连接Ace

app.factory('authInterceptor', ['$rootScope', '$q', '$window', '$injector',
function($rootScope, $q, $window, $injector) {
    return {
        response: function(response) {
            if (response.status === 401) {
                // handle the case where the user is not authenticated
            } else {
                var Ace = $injector.get('Ace');
                Ace.getCurrentUser().then(function() {
                    console.log("Got current user");
                });
            }
            return response || $q.when(response);
        }
    };
  }
]);

另一种解决方法是在 run() 块而不是 config() 块中注册拦截器,但请记住,在执行 run() 之前,对 $http 的任何调用都与 authInterceptor 无关/p>

【讨论】:

  • 谢谢,至少部分有效。现在我可以发送一个请求,但它会在一个无限循环中获取库存,一遍又一遍地调用 Ace.getCurrentUser()....
猜你喜欢
  • 2019-11-06
  • 2023-03-04
  • 2020-11-12
  • 1970-01-01
  • 2013-02-04
  • 2010-10-27
相关资源
最近更新 更多