Search code examples
angularangular-http-interceptors

Disable Angular HttpInterceptor for some call


I have an angular application with an HttpInterceptor that catch the http errors to show some dialog, common to all my application.

I would like to disable the interceptor for some specific calls but I prefer to disable the default behaviour where i call the http, instead of write an exception into the interceptor. Anyone have found this problem?

I can be more specific with an example, if needed.

Regards

Davide


Solution

  • You can use HttpBackend to do this.

    Description: When injected, HttpBackend dispatches requests directly to the backend, without going through the interceptor chain.

    Using: You can use same like HttpClientby import it from @angular/common/http

    Example:

    import { HttpClient, HttpBackend } from '@angular/common/http';
    
    ...
    
    @Injectable({
      providedIn: 'root'
    })
    export class HttpHelperService {
    
      private httpClient: HttpClient;
    
      constructor( httpBackend: HttpBackend) { 
         this.httpClient = new HttpClient(httpBackend);
      }
    
      // use like normal with HttpClient. However, should name it carefully to separate which http request go throught interceptor and which is not
      put(path: string, body: Object = {}): Observable<any> {
        return this.httpClient.put(
          `${this.URL}${path}`,
          JSON.stringify(body)
        ).pipe(catchError(this.formatErrors));
      }
    
    ....
    

    ref: https://angular.io/api/common/http/HttpBackend