Search code examples
angularangular-servicesangular-httpangular-http-interceptors

angular - show notification based on HTTP response


I use middleware for my back-end which processes each exception and produces JSON response which looks as follows:

{"error":"System.Exception: 'You must be logged in to perform this action.'"}

In my Angular app I would like to show a notification carrying the exception text each time the exception occurs, but I'm not entirely sure about how to implement this.

I wonder if should use HttpInterceptor for that - I'm also not quire sure how to register them properly - they should be registered in root.module.ts to work app-wide, right?

Could someone recommend a workaround or provide code examples please?


Solution

  • Definitely use an interceptor.

    Start by creating a service and transform it to an interceptor :

    import { Observable } from 'rxjs/Observable';
    
    import {
      HttpEvent, HttpHandler, HttpInterceptor, HttpRequest, HttpResponse
    } from '@angular/common/http';
    import { Injectable } from '@angular/core';
    
    @Injectable()
    export class ErrorHandlerInterceptor implements HttpInterceptor {
    
      constructor() { }
    
      intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        return next
          .catch(err => { /* Display your error here */})
          .handle(req);
      }
    }
    

    Next, you will need to provide it in your module :

      providers: [
        { provide: HTTP_INTERCEPTORS, useClass: ErrorHandlerInterceptor, multi: true },
      ]