jju*_*9jj 3 javascript interceptor angularjs
我尝试在http拦截器中执行http.post调用,但是我得到了一个
Circular dependency found: $http <- Ace <- authInterceptor <- $http <- $templateRequest <- $compile
Run Code Online (Sandbox Code Playgroud)
我明白为什么,但我不知道如何解决它...仍然新的角度和有点混乱的时候,我希望你可以帮助我:) 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');
});
Run Code Online (Sandbox Code Playgroud)
您正在试图确定$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 Code Online (Sandbox Code Playgroud)
另一种解决方法是在run()块而不是config()块中注册拦截器,但请记住,在run()执行之前,任何$http与之无关的调用都与authInterceptor