I have written an Http Interceptor
in Angular 6 .
The goal is to reload the home page when 302 status
is returned.
I am currently not able to understand why the HttpInterceptor
is behaving the way it is
Code :
API call which returns 302 status
is below.
this._service.checkStatus()
calls back end API which returns 302 http status
API Code :
public checkStatus() : void {
this._service.checkStatus().subscribe(
(data) => console.log('success In checkStatus '),
(error)=>console.log('error In checkStatus')
);
}
Interceptor Code :
export class MyInterceptor implements HttpInterceptor{
constructor(){
}
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
console.log('inside interceptor' );
return next.handle(request).pipe(
tap(
event =>{
},
error=>{
console.log(error);
if (error instanceof HttpErrorResponse) {
if (error.status === 302) {
window.location.reload();
}
}
}
)
);
}
}
Issue :
Now the issue is when 302 status
is returned , the line (error)=>console.log('error In checkStatus')
still gets executed in API - checkStatus
call.
My question is ,why error handler in API call still gets called .
That is , after 302 is returned , the page gets reloaded with window.location.reload()
But the error handler (error)=>console.log('error In checkStatus')
still gets invoked.
What needs to be done to prevent execution of Error handler code inside checkStatus
API ?
Try it with catchError.
return next.handle(request).pipe(
tap((event: HttpEvent<any>) => {
console.log('tap', event);
}),
catchError(error => {
console.log('catchError', error);
if (error instanceof HttpErrorResponse) {
if (error.status === 302) {
window.location.reload();
}
}
return throwError(error);
})
)