Issue
I am showing a loading bar using HTTP interceptor in my angular project that shows loader whenever an HTTP request is sent to the serve.
loader.service.ts
import { Injectable } from '@angular/core';
import { Subject } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class LoaderService {
isLoading = new Subject<boolean>();
constructor() { }
show() {
this.isLoading.next(true);
}
hide() {
this.isLoading.next(false);
}
}
loader-interceptor.ts
import { Injectable } from '@angular/core';
import { HttpEvent, HttpHandler, HttpInterceptor, HttpRequest } from '@angular/common/http';
import { Observable } from 'rxjs';
import { finalize } from 'rxjs/operators';
import { LoaderService } from '../services/loader.service';
@Injectable()
export class LoaderInterceptorService implements HttpInterceptor {
constructor(private loaderService: LoaderService) { }
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
this.loaderService.show();
return next.handle(request).pipe( finalize( () => this.loaderService.hide()) );
}
}
Problem is that loader hides before the data has been loaded. This happens especially if there is a lot of data. I want the loader not to hide unless all the requests have been resolved so that's user is not able to interact with forms etc. unless the data is loaded. The loader HTML uses overlay CSS to block users to interact with forms until data has arrived.
In another project, I used to do call these hide/show methods in service calls when I was subscribing to the service methods in every component. I want to avoid this because this requires me to add this code again and again in every component.
Any solution for this problem ?
PS: Is it problematic to handle loader when there are multiple HTTP requests in different components simultaneously ?
Solution
You should be hiding the loader on response:
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
this.loaderService.show();
return next.handle(req).pipe(map(event => {
if (event instanceof HttpResponse) {
this.loaderService.hide();
}
return event;
}));
}
Answered By - Joel Joseph
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.