I have implemented Http Interceptor and showing spinner when service is initiated and hiding spinner when service is success/fails.
Code Sample:
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return next.handle(req).pipe(
tap((event: HttpEvent<any>) => {
if (event instanceof HttpResponse && event.body.errCode != undefined) {
// show_spinner
}
}),
finalize(()=>{
// hide_spinner
})
}
For example there are two service calls both occurs at same time; therefore spinner will be shown corresponding to both calls but first service is finished in 2 secs and second in 5 secs; Now spinner will be hidden after the first call is finished, will not be able to acknowledge second service call.
I would like to answer my own question, so one can refer to the solution to above question/problem.
Firstly, declare a global variable (initialize it as 0) used as a counter for active service calls.
Secondly, for each service intercepted increment count(counter variable) and when service call is finalize decrement the count(counter variable).
Lastly, if service count is equal to zero hide the spinner else show the spinner.
Example: Define an interceptor service in general for intercepting HTTP Requests.After that in interceptor service :
service_count = 0; // initialize the counter.
constructor(
private _route:Router
) {}
intercept(req: HttpRequest<any>, next: HttpHandler):Observable<HttpEvent<any>> {
this.service_count++; // increment the count for each intercepted http request.
// show spinner.
return next.handle(req).pipe(
finalize(() => {
this.service_count--;
// decrement when service is completed (success/failed both
handled when finalize rxjs operator used)
if (this.service_count === 0) {
// hide spinner
}
})
);
}