Angular JS解决循环依赖

时间:2015-08-05 07:56:28

标签: javascript angularjs interceptor

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

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

我知道为什么,但我不知道如何解决它...仍然新的角度和有点混乱的某个时候,我希望你可以帮助我:) Heres是我的代码:

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

1 个答案:

答案 0 :(得分:8)

您试图通过将$http注入authInterceptor来定义$httpProvider的预处理功能,但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无关。 Geocoder