I am using angular 4.x
In development environment, if someone restarts the server or if user logs out from another tab and then the user keeps trying to perform some action from another tab, he/she keeps seeing the error on page.
I want centralize solution using Angular's HTTP service so that if a user is trying to perform any operation and an error due to session expiration occurs, we want to refresh the page.
So here's an example of an HttpInterceptor class that I got from here (full plunker here).
@Injectable()
export class MyHttpLogInterceptor implements HttpInterceptor {
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
console.log('processing request', request);
const customReq = request.clone({
headers: request.headers.set('app-language', 'it')
});
return next
.handle(customReq)
.do((ev: HttpEvent<any>) => {
if (ev instanceof HttpResponse) {
console.log('processing response', ev);
}
})
.catch(response => {
if (response instanceof HttpErrorResponse) {
console.log('Processing http error', response);
}
return Observable.throw(response);
});
}
}
The catch
block is probably what you're interested in. You could inspect the error and check if it came from a session expire, then react to it properly.
You need to provide this Interceptor in your app.module.
providers: [
{ provide: HTTP_INTERCEPTORS, useClass: MyHttpLogInterceptor, multi: true }
]