angularangular-ui-routerangular-http-interceptorsangular-routerlinkangular-router-events

Angular display error banner after API error on all pages throughout the application


I have many components in angular and I am trying to display static error banner on all pages in case of GET API error related with that component. Through Interceptor I am able to get the API error but not sure how I can display banner throughout the application. I want to keep the router URL as it is on whichever page user is there.

Created Interceptor and It is working fine but next step is display error banner for all pages


Solution

  • 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>