我有这样的拦截器代码:
var responseError = function(rejection) {
if (rejection.status === 401 || rejection.status === 403) {
authService.renewToken($localStorage.refreshToken).then(function () {
});
}
}
并确定,在此代码的头部我包括authService“injector”,如
['$q', '$injector', '$location', '$localStorage', '$rootScope', '$window', 'authService',
function($q, $injector, $location, $localStorage, $rootScope, $window, authService) {...
并且在服务中我有这样的代码:
var renewToken = function(token) {
var data = /**/
var deferred = $q.defer();
$http.post('token', data, {
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
})
.success(function(response) {
deferred.resolve(response);
}).error(function (err) {
deferred.reject(err);
});
return deferred.promise;
};
但当我落入此代码时,我得到:
Uncaught Error: [$injector:cdep] Circular dependency found: $http <- authService <- authInterceptorService <- $http <- $templateRequest <- $route
当我在拦截器中遇到异常时,如何更新我的令牌?
答案 0 :(得分:1)
在拦截器中,您不必包含authService
,只注入$injector
你的responseError函数应该是这样的:
var responseError = function(rejection) {
if (rejection.status === 401 || rejection.status === 403) {
var authService = $injector.get('authService');
authService.renewToken($localStorage.refreshToken).then(function () {
});
}
}
这是通过循环依赖性错误的解决方法。