Reputation: 327
I'm building an AngularJs app working with a custom API, the latter needs a valid authorization token, if it isn't, my API returns a 4O1 HTTP status code.
Thus, I use a http interceptor which is meant to ask for a new token before retrying the previous request.
app.factory('httpResponseErrorInterceptor', ['$q', '$injector', function($q, $injector, $http) {
return {
'responseError': function(response) {
if (response.status === 401) {
// should retry
let deferred = $q.defer();
let $http = $injector.get('$http');
$.ajax({
url : PUBLIC_API_URI,
type : 'HEAD',
beforeSend : function(request) {
request.setRequestHeader('Authorization', api_access_key);
},
success : function(result, status, xhr) {
console.log("error -> ok : should retry");
deferred.resolve(xhr.getResponseHeader('Authorization'));
},
error : function(xhr, status, error) {
console.log("error -> bad : should give up");
deferred.resolve(null);
}
});
console.log(deferred.promise);
if(deferred.promise == null)
return $q.reject(response);
response.config['Authorization'] = api_access_key = deferred.promise;
return $http(response.config);
}
return $q.reject(response);
}
};
}]);
I used JQuery.ajax in my interceptor because I guessed that using $http was causing the infinite loop when the token-renewal request resulted in an error. But it still causes an infinite loop on error : original-request -> renewal-request ...
Upvotes: 3
Views: 1029
Reputation: 8632
i don't see the complete log of the error but i guess the problem could be related to the injection of $http
service (that is still there even if you're using $.ajax) inside an http interceptor. this will cause a circular dependency because angular will face an infinite loop trying to resolve both the dependency of $http
and its interceptor.
see my previous answer here
if you need to make an ajax call try injecting the service "by need"
angular.module('myApp').factory('interceptor', function($injector){
return {
'responseError': function(response) {
var http = $injector.get('$http');
http.get..
}
}
});
Upvotes: 2