ze.espogeira ze.espogeira -4 years ago 187
Javascript Question

angular defered resolve undefined

angular stuff is making me crazy! tha app uses Bearer authentication, there is an errorInterceptor like this

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


it almost works, 1st 401 response issues a "refreshToken" request then all subsequent requests are re-sent with the new token.
The problem i'm facing is in the line

deferred.resolve(result);


and although result is the expected object, when promise function is invoked its argument is undefined!

the promise function

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
//
}


Can anyone please help?
thank you

Answer Source

Just use .then() instead of .success(), its deprecated since Angular 1.5 anyway and got removed in 1.6. With .success() promise chaining is not possible, as it doesn't return a new promise to resolve.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download