I've made an interceptor in my application that detects session loss (server sends an HTTP 419). In this case, I need to request a new session from the server, and then I would like to send the original request again automatically.
Maybe I could save the request in a request interceptor, and then send it again, but there might be a simpler solution.
Note that I have to use a specific webservice to create the session.
angular.module('myapp', [ 'ngResource' ]).factory(
'MyInterceptor',
function ($q, $rootScope) {
return function (promise) {
return promise.then(function (response) {
// do something on success
return response;
}, function (response) {
if(response.status == 419){
// session lost
// create new session server-side
// Session.query();
// then send current request again
// ???
}
return $q.reject(response);
});
};
}).config(function ($httpProvider) {
$httpProvider.responseInterceptors.push('MyInterceptor');
});
You're on the right path, you basically store the request in a queue and retry it after you've re-established the session.
Check out this popular module: angular http auth (https://github.com/witoldsz/angular-http-auth). In this module, they intercept 401 responses but you can model your solution off of this approach.
The
responseError
method ofhttpInterceptor
have to be like this:And the magic happens here:
Here is my solution using promises for those interested. Basically you need to request a new session, and wait for the response before sending a new request corresponding to the original request (using response.config). By returning the promise $http(response.config) you ensure that the response will be treated as if it was the original request.
(syntax may not be the best as I'm new to promises)
More or less the same solution, translated in typescript:
Hope this help.