DEV Community

Cover image for Making API call bypassing Interceptor if one is configured in Angular
Nikhil Dhawan for This is Angular

Posted on • Edited on

Making API call bypassing Interceptor if one is configured in Angular

Hi All, if you have worked on some Angular project and used backend communication with API in which want to add some auth header to every outgoing request you must have used Interceptor to achieve that.
But suppose you have a call to be made without passing through Interceptor so what approach you will use? We are going to discuss one approach for that and if you have some other way also, please be free to share that in the comments.

Setting up the project

After initial setup of Angular project lets add the below HTML code in HTML template file

<button (click)="callWitInterceptor()" >Call using interceptor</button>
<br>
<hr>
<button (click)="callWithoutInterceptor()" >Call without interceptor</button>
Enter fullscreen mode Exit fullscreen mode

And below in typescript file for our first function callWitInterceptor, for the other one we will add later in the article.

constructor(private http: HttpClient) {}
callWitInterceptor() {
    this.http.get('https://dog.ceo/api/breeds/image/random').subscribe();
  }
Enter fullscreen mode Exit fullscreen mode

And interceptor function looks like below and it is to be added to NgModule under providers array.

intercept(request: HttpRequest<unknown>, next: HttpHandler): Observable<HttpEvent<unknown>> {
    console.log('Through interceptor')
    return next.handle(request);
  }
Enter fullscreen mode Exit fullscreen mode

You can also refer StackBlitz project from below for a working example.
So now if we click on Button Call using interceptor we will be able to see console output we have in interceptor like below.
image
So now to bypass the interceptor we can use HttpBackend. For more details about it, please refer to this. When injected, HttpBackend dispatches requests directly to the backend, without going through the interceptor chain. So as per the definition, we can surely use it for our current use case.
Now lets add the function for Button Call without interceptor in typescript file and don't forget to inject HttpBackend in constructor.

constructor(private http: HttpClient, private httpBackend: HttpBackend) {}
  callWithoutInterceptor() {
    this.httpBackend
      .handle(new HttpRequest('GET', 'https://dog.ceo/api/breeds/image/random'))
      .subscribe();
  }
Enter fullscreen mode Exit fullscreen mode

Now when we click on the Button we will notice that the console is not printed but in the network tab, we can see the API call made.

image

Hereby using HttpBackend we were able to bypass the application-wide interceptor. Hope you found this interesting and learned something new. If you liked it please share it with your friends or if any suggestions reach me out on Twitter or comment below. Till next time Happy Learning!

Top comments (0)