棱 Angular 分明的东西让我发疯!该应用程序使用 Bearer 身份验证,有一个这样的 errorInterceptor
function errorInterceptor($injector, $log, $location) {
var inFlight = null;
var authInterceptorServiceFactory = {};
var _request = function (config) {
config.headers = config.headers || {};
var oauthToken = $injector.get('oauthService').getAuthorizationHeader();
if (oauthToken) {
config.headers.Authorization = oauthToken;
}
return config;
}
var _responseError = function (rejection) {
debugger
var deferred = $injector.get('$q').defer();
switch(rejection.status){
case 401:
console.log('401');
if(inFlight == null){
var authService = $injector.get('oauthService');
inFlight = authService.refreshToken() //this is just a $http call
}
inFlight
.then(function (response) {
_retryHttpRequest(rejection.config, deferred)
.success(function (result) {
deferred.resolve(result);
})
.error(function(err, status) {
deferred.reject(err);
})
.finally(function() {
inFlight = null;
});
$injector.get('oauthService').setLocalStorageData(response.data);
},
function (err, status) {
$injector.get('oauthService').logOut();
});
break;
}
return deferred.promise;
}
var _retryHttpRequest = function (config, deferred) {
var $http = $http || $injector.get('$http');
return $http(config);
}
authInterceptorServiceFactory.request = _request;
authInterceptorServiceFactory.responseError = _responseError;
return authInterceptorServiceFactory;
}
它几乎可以工作,第一个 401 响应发出“refreshToken”请求,然后所有后续请求都使用新 token 重新发送。 我面临的问题是在行
deferred.resolve(result);
虽然 result 是预期的对象,但当调用 Promise 函数时,它的参数是未定义的!
promise 函数
sidebarService.getMenu()
.success(sidebarReady)
.error(sidebarReadyError);
function sidebarReady(items) {
//when errorInterceptor catches the error
//and re-sends, when it resolves this funciton, argument is undefined
//
}
有人可以帮忙吗? 谢谢
最佳答案
只需使用 .then() 而不是 .success(),它从 Angular 1.5 起就已被弃用,并在 1.6 中被删除。使用 .success() 不可能实现 promise 链接,因为它不会返回要解析的新 promise 。
关于javascript - Angular 延迟解析未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42959386/