This is how I implement Interceptor to show loading for all Http request.
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
if(myCondition == true)
{
// my loading start showing here
return next.handle(req).pipe(
finalize(() => {
// I hide my loading here
}) );
}
return next.handle(req).pipe(
finalize(() => { }));
}
but my Http request has many data and the backend take almost 10 seconds to complete.
I just need to hide the loading only after the backend operation is finished.
But, by using the above code, the loading is hide before the backend is finished.
Do I need to handle HttpRespond like this example?
UPDATE:
I found why it is causing, I've updated my code.
I have a condition "if(myCondition == true)", I only show loading only if the condition is true. But we must have return for the intercept method, right?
So I put the "return" outside of this condition.
This return causing issue and that's why the loading disappears.
So how can I fix for a scenario like this?
You need to manage certain scenarios while you make an API call.
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
this.loadingService.show(); //Initiate loader
return next.handle(req).do((event: HttpEvent<any>) => {
if (event instanceof HttpResponse) {
this.loadingService.hide();
//Closing loader when you receive reponse
}
}, (err: any) => {
if (err instanceof HttpErrorResponse) {
this.loadingService.hide();
//Closing loader when you have Error
}
})
}