I have a feature in my code that monitors requests and responses.
I attempted to display a spinner only if a request takes more than 1 second:
@Injectable()
export class LoadingInterceptor implements HttpInterceptor {
private requests: HttpRequest<any>[] = [];
constructor(private spinnerService: SpinnerService) {}
intercept(
req: HttpRequest<any>,
next: HttpHandler
): Observable<HttpEvent<any>> {
this.requests.push(req);
this.spinnerService.isLoading.next(true);
return new Observable((observer) => {
next.handle(req).subscribe(
(event) => {
if (event instanceof HttpResponse) {
this.removeRequest(req);
observer.next(event);
}
},
() => {
this.removeRequest(req);
},
() => {
this.removeRequest(req);
}
);
});
}
private removeRequest(request: HttpRequest<any>) {
const index = this.requests.indexOf(request);
if (index >= 0) {
this.requests.splice(index, 1);
}
this.spinnerService.loadingStop.next();
this.spinnerService.loadingStop.complete();
this.spinnerService.isLoading.next(this.requests.length > 0);
}
}
The Spinner service implementation is as follows:
constructor() {
this.isLoading
.pipe(debounceTime(100), delay(1000), takeUntil(this.loadingStop))
.subscribe((status: boolean) => (this.loadingStatus = status));
}
To achieve the desired behavior, I included the following code snippet:
.pipe(debounceTime(100), delay(1000), takeUntil(this.loadingStop))
However, despite these efforts, I am unable to get it to work as intended. How can I ensure the spinner is displayed when response time exceeds 1 second?