Angular Make Connect Between Interceptor and Other Component

As you know, interceptor is one of best solution to listen to all HTTP request also handle global error like 500 and connection errors depends on all of the requests in project, without need to write code and handle inside any services,One of the challenges we have been inside interceptors of angular is, we can’t have direct control of other components, also we haven’t use viewChild inside interceptors like other components, that’s why we must use this way to solve this problem:

First of all, we must make a service to work likes a bridge for us, in this service we should use a Subject form RXJS lib that helps us to make an event with management for dispatch with next method, next method get a parameter as once argument by type boolean, we use a function named showError to serve our needed data form interceptor to this service.

connector.service.t

import { Subject } from "rxjs";
import { Injectable } from "@angular/core";
@Injectable()
   export class ConnectorService {
      errorEvent: Subject<boolean> = new Subject<boolean>();
      showError(event) {
         this.errorEvent.next(true);
      }
}

In terms of interceptor file, the interceptor is like a layer above all of your HTTP requests for more information about this read more in the Angular documentation.

http.interceptor.ts

import {Observable, throwError as observableThrowError} from 'rxjs';
import {catchError, concatMap, tap, take, retry} from 'rxjs/operators';
import {Injectable} from '@angular/core';
import {
    HttpErrorResponse,
    HttpEvent,
    HttpHandler,
    HttpInterceptor,
    HttpRequest,
    HttpResponse
} from '@angular/common/http';
@Injectable()
export class MyHttpInterceptor implements HttpInterceptor {
  
    constructor(private connectorService:ConnectorService) { }
 
    intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return next
            .handle(request).pipe(
                tap((ev: HttpEvent<any>) => {
                    if (ev instanceof HttpResponse) {
                        this.errorGlobalService.showError(false);
                        
                    }
                }), 
                catchError(response => {
                    if (response instanceof HttpErrorResponse) {
                        switch (response.status) {
                            //Error number for example: 500, 400 etc.
                            case 0: 
                              this.connectorService.showError(true);
    
                            break;
 
                    }
 
                    return observableThrowError(response);
                })
            );
    }
}

Finally, for use that you only need to subscribe errorEvent form connector service and get served data form interceptor inside result return value.

sample.component.ts

@Component({
  selector: 'sample',
  templateUrl: './sample.component.html',
})
export class SampleComponent {
 
  constructor( private connectorService:ConnectorService ) { 
 
    this.connectorService.errorEvent.subscribe((result) => {
      console.log('get result of event as boolean', result)
    })
}
 
}

Now, you can easily check all request error (in this example) in all of your Components and show message or error bar for errors has happened.

In conclusion, Interceptor with connector help you’re to make a global error or event manager as a layer above of your direct request, and with connector trick, you can easily use and check it in all Components.

(Visited 16 times, 1 visits today)

Leave a comment

Your email address will not be published. Required fields are marked *