I am attempting to show a loading indicator whenever an Http Request is sent. Although I am using Angular's Http Interceptor, the style of the indicator never seems to update.
In my app.component.html, I have included a loading indicator.
<div [style.display]="visibilityOfLoadingIndicator">
<mat-progress-bar mode="indeterminate" color="warn" ></mat-progress-bar>
</div>
Below is the app.component.ts:
export class AppComponent {
visibilityOfLoadingIndicator = 'none';
constructor(public loadingIndicatorService: LoadingIndicatorService) {
this.loadingIndicatorService.getLoadingIndicator()
.subscribe(visibility => {
this.visibilityOfLoadingIndicator = <string> visibility;
});
}
}
This is the HttpLoadingIndicatorService.ts:
@Injectable({
providedIn: 'root'
})
export class LoadingIndicatorService implements HttpInterceptor {
private display;
private loadingIndicator: EventEmitter<string>;
constructor() {
this.loadingIndicator = new EventEmitter<string>();
}
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
const started = Date.now();
console.log('Request started');
this.display = 'block';
this.updateVisibility(this.display);
return next.handle(req)
.pipe(
finalize(
() => {
const elapsed = Date.now() - started;
const msg = `${req.method} "${req.urlWithParams}"
in ${elapsed} ms.`;
console.log(msg);
this.display = 'none';
this.updateVisibility(this.display);
}
)
)
;
}
updateVisibility(state: string) {
this.loadingIndicator.emit(state);
}
getLoadingIndicator() {
return this.loadingIndicator;
}
}
The service appears to be functioning correctly based on the console output:
->Request started
->http-loading-indicator.service.ts:24 GET "http://localhost:8080/api/film"
in 2164 ms.
However, the style of the indicator is not updating. Should I consider creating an Observable?