How to Create an Angular HttpInterceptor?

Angular 4.3 brought us a new easier way to handle HTTP requests with the HttpClient library. I mentioned how powerful this tool is in my previous post; Introduction to Angular HttpClient

Now it’s time to explore another of the powerful angular features: interceptors. Interceptors provide a mechanism to intercept and/or mutate outgoing requests or incoming responses.

Interceptors are a way to do some work for every single HTTP request or response.

Here are a few examples of common use cases for interceptors:

  • Add a token or some custom HTTP header for all outgoing HTTP requests
  • Catch HTTP responses to do some custom formatting (i.e. convert CSV to JSON) before handing the data over to your service/component
  • Log all HTTP activity in the console

To implement an interceptor, you’ll want to create a class that’s injectable and that implements HttpInterceptor. The class should define an intercept method to correctly implement HttpInterceptor. The intercept method takes two arguments, req and next, and returns an observable of type HttpEvent.

  • req is the request object itself and is of type HttpRequest.
  • next is the http handler, of type HttpHandler. The handler has a handle method that returns our desired HttpEvent observable.

Below is a basic interceptor implementation;

import { Injectable } from '@angular/core';
import { HttpEvent, HttpRequest, HttpHandler, HttpInterceptor, HttpResponse } from '@angular/common/http';
import { Observable, of } from 'rxjs';
import { tap, delay } from 'rxjs/operators';

@Injectable()
export class AngularInterceptor implements HttpInterceptor {
  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    
    // DO ANYTHING YOU WANT
    
    return next.handle(request);
  }
}

To wire-up our interceptor, provide it in the app module or a feature module using the HTTP_INTERCEPTORS token:

@NgModule({
  declarations: [
    ...
  ],
  imports: [
    ...
  ],
  providers: [
  { provide: HTTP_INTERCEPTORS, useClass: AngularInterceptor, multi: true },
    ...
  ],
  bootstrap: [AppComponent]
})
export class AppModule {}