I am making an application-level “loading spinner” with the help of the HttpInterceptor
in Angular 16.
In appservicesinterceptor.service.ts
I have:
import { Injectable } from '@angular/core';
import { HttpInterceptor,HttpRequest, HttpHandler, HttpEvent } from '@angular/common/http';
import { Observable } from 'rxjs';
import { finalize } from 'rxjs/operators';
import { SpinnerService } from './spinner.service';
@Injectable({
providedIn: 'root'
})
export class HttpInterceptorService implements HttpInterceptor {
constructor(private spinnerService: SpinnerService) { }
public intercept(
req: HttpRequest<any>,
next: HttpHandler
): Observable<HttpEvent<any>> {
this.spinnerService.show();
return next.handle(req).pipe(
finalize(() => {
this.spinnerService.hide();
})
);
}
}
In appservicesspinner.service.ts
:
import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class SpinnerService {
private spinnerCounter = new BehaviorSubject<number>(0);
spinnerCounter$ = this.spinnerCounter.asObservable();
public show() {
this.spinnerCounter.next(this.spinnerCounter.value + 1);
}
public hide() {
this.spinnerCounter.next(this.spinnerCounter.value - 1);
}
}
I have imported the spinnerService
in appapp.component.ts
and added the spinner to appapp.component.html
.
<app-loading-spinner *ngIf="spinnerService.spinnerCounter$ | async"></app-loading-spinner>
The problem
For a reson I have been unable to figure out, the app-loading-spinner
component is never displayed between http reqiests.
Stackblitz
I have added a stackblitz with the current code.
Questions
- What am I doing wrong?
- What is the easiest and most reliable way to fix this issue?