You can create an ErrorMessageService
to establish a connection between your interceptor class and your application's base component (e.g. your AppComponent
). The latter would eventually display the error-messages.
ErrorMessageService
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class ErrorMessageService {
errorMessage: string;
isErrorMsgVisible = false;
displayError(errorMessage) {
this.errorMessage = errorMessage;
this.isErrorMsgVisible = true;
}
hideError() {
this.errorMessage = '';
this.isErrorMsgVisible = false;
}
}
In your Http Interceptor you have to import the ErrorMessageService
and call displayError()
:
constructor(private errorMessageSvc: ErrorMessageService) {}
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return next.handle(request).pipe(
catchError((error) => {
const errorMessage = error.error;
this.errorMessageSvc.displayError(errorMessage);
// ....
// Code omitted for brevity
})
);
}
In your Base Component TS (e.g. your AppComponent.ts) you have to import the ErrorMessageService
:
constructor(public errorMessageSvc: ErrorMessageService) {}
In the upper part of your Base Component HTML (e.g. in AppComponent.html
) you could eventually display an error-message whenever somewhere in your application an error occurs:
<div *ngIf="errorMessageSvc.isErrorMsgVisible">
<p>{{ errorMessageSvc.errorMessage }}</p>
<button (click)="errorMessageSvc.hideError()">Close</button>
</div>