Implementing a loaderInterceptor to handle spinner display and hiding functionality for multiple HTTP calls on a page.
Issue: Experiencing flickering behavior in the spinner between consecutive HTTP calls.
I need a solution to only display the spinner when the first HTTP call is made and hide it once all calls are completed.
Here is the code snippet for my Loader Interceptor:
@Injectable()
export class MyLoaderInterceptor implements HttpInterceptor {
private requests = 0;
removeloaderTime: any;
constructor(private loaderService: LoaderService) { }
private stop = ((req: any): void => {
this.removeloaderTime = setTimeout(() => {
if (this.requests > 0) {
this.requests--;
}
if (this.requests === 0) {
// Hide Loader
// loaderService.hide()
clearTimeout(this.removeloaderTime);
}
}, 2000);
})
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
this.requests++
// Show Loader
// loaderService.show()
return new Observable(observer => {
const subscription = next.handle(req)
.subscribe(
event => {
if (event instanceof HttpResponse) {
this.stop(req);
observer.next(event);
}
},
err => {
this.stop(req);
observer.error(err);
},
() => {
this.stop(req);
observer.complete();
});
return () => {
this.stop(req);
subscription.unsubscribe();
};
});
}
}