Using the interceptor, I want to display a loading spinner while waiting for subscriptions to complete. This approach works well in individual components by showing and hiding the spinner accordingly:
ngOnInit() {
this.spinnerService.show();
this.service.methodName().subscribe(data => {
},error => {
},() => {
this.spinnerService.hide();
})
}
However, implementing this functionality in the interceptor poses a challenge. The spinner briefly appears only when the request is made, disappearing quickly even for longer requests:
if (request.url.includes(this.apiUrl)) {
this.spinnerService.show();
let headers = new HttpHeaders();
headers = headers.append('Content-Type', 'application/json');
headers = headers.append('Authorization', `Bearer ${token}`);
cloneRequest = request.clone({ headers: headers });
} else {
cloneRequest = request.clone();
}
return next.handle(cloneRequest).pipe(map(response => {
this.spinnerService.hide();
return response;
})).pipe(catchError(error => {
let errorMessage = 'An unexpected error occured';
if (error.error && error.error.message) {
errorMessage = error.error.message;
}
// TODO: Error notifications are currently disabled.
if (request.url.includes('login')) {
this.notificationService.showError(errorMessage);
}
return throwError(error)
}));