I am using a promise to query a service from my web-app. If the token is invalid, I now want to ask the user for the credentials using a modal, query a new token from the backend, rerun the failed request and return into the success block of the promise of my initial request to continue as nothing happened.
So I setup an error interceptor to catch a 401, and open a modal asking for credentials. Then I use the existing AuthService to query a token and return $http(response.config) with the adjusted token.
Here is my initial request:
MyService.getData().then(
function(result) {
console.log("process data");
}
, function(response) {
console.log("error occurred retrieving data");
}
);
Here is my error interceptor, reacting on 401s:
Restangular.setErrorInterceptor(
function(response) {
if (response.status === 401) {
console.log("interceptor catches");
var modal = $uibModal.open({
templateUrl: "frame/view/Relogin.html",
controller: "ReloginController",
});
console.log("opened modal");
return modal.result.then(function(data) {
console.log("get new token");
return AuthService.authenticate(data[0], data[1]).then(
function (token) {
console.log("set new token");
},
function(){
console.log("failed getting new token");
})
.then(function() {
console.log("now rerun request");
return $http(response.config);
});
});
}
return $q.reject(response);
});
What happens now, is that the interceptor catches the 401, and opens the modal. But instead of waiting for the user input now and querying the backend for a new token, the error block of the promise is now accessed.
So the console output is:
interceptor catches
opened modal
error occurred retrieving data
get new token
set new token
now rerun request
But I wanted it to be:
interceptor catches
opened modal
get new token
set new token
now rerun request
process data
I assume there is a mistake in using promises... Can someone help?
Thanks!