I made spinner interceptor for http request. For every http request spinner is showing.
But some web requests are relatively fast, in this case, the spinner will become a flicker in the web page.
I want to make some delay for spinner but i don't have idea how.
Spinner component
<ng-container *ngIf="loading$ | async">
<mat-progress-bar mode="indeterminate" color='warn'>
</mat-progress-bar>
export class SpinnerComponent implements OnInit {
loading$;
constructor(private spinnerService: SpinnerService) { }
ngOnInit() {
this.loading$ = this.spinnerService.isLoading$
.pipe(
delay(0)
);
}
}
Spinner Service
export class SpinnerService {
isLoading$ = new Subject<boolean>();
show() {
this.isLoading$.next(true);
}
hide() {
this.isLoading$.next(false);
}
}
Spinner Interceptor
export class SpinnerInterceptor implements HttpInterceptor {
requestCount = 0;
constructor(private spinnerService: SpinnerService) { }
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
this.requestCount++;
this.spinnerService.show();
return next.handle(request)
.pipe(
finalize(() => {
this.requestCount--;
if (this.requestCount === 0) {
this.spinnerService.hide();
}
})
);
}
}