Tutorial

Angular HttpClient: Interceptors

Angular
This tutorial is out of date and no longer maintained.

Introduction

Angular’s HttpInterceptors provide a mechanism to intercept and or mutate outgoing requests or incoming responses. They are very similar to the concept of middleware with a framework like Express, except for the frontend. Interceptors can be really useful for features like caching and logging.

Note: The content here applies to Angular 4.3+.

In this article, you will learn about using HttpInterceptors in an Angular project.

Basic Setup

To implement an interceptor, you will 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, request and next, and returns an observable of type HttpEvent.

  • request 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. This particular interceptor simply uses the RxJS do operator to log the value of the request’s filter query param and the HttpEvent status to the console. The do operator is useful for side effects such as this:

interceptors/my.interceptor.ts
import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpHandler, HttpRequest, HttpEvent, HttpResponse }
  from '@angular/common/http';

import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/do';
@Injectable()
export class MyInterceptor implements HttpInterceptor {
  intercept(
    req: HttpRequest<any>,
    next: HttpHandler
  ): Observable<HttpEvent<any>> {
return next.handle(req).do(evt =&gt; {
  if (evt instanceof HttpResponse) {
    console.log('---&gt; status:', evt.status);
    console.log('---&gt; filter:', req.params.get('filter'));
  }
});

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

app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';
import { MyInterceptor } from './interceptors/my.interceptor';

Multiple interceptors

You could define multiple interceptors with something like this:

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

The interceptors will be called in the order in which they were provided. So with the above, MyInterceptor would handle HTTP requests first.

Modifying Requests

HttpRequest objects are immutable, so in order to modify them, we need to first make a copy, then modify the copy and call handle on the modified copy. The request object’s clone method comes in handy to do just that. Here’s a simple interceptor that sets the filter query param to a value of completed:

@Injectable()
export class MyInterceptor implements HttpInterceptor {
  intercept(
    req: HttpRequest<any>,
    next: HttpHandler
  ): Observable<HttpEvent<any>> {
    const duplicate = req.clone({ params: req.params.set('filter', 'completed') });

    return next.handle(duplicate);
  }
}

And here’s a last example of an interceptor that changes every occurrence of the word pizza in the body of the request to the pizza emoji (🍕). Requests without a body will just pass-through by returning our original request with return next.handle(req):

@Injectable()
export class MyInterceptor implements HttpInterceptor {
  intercept(
    req: HttpRequest<any>,
    next: HttpHandler
  ): Observable<HttpEvent<any>> {
    if (req.body) {
      const duplicate = req.clone({ body: req.body.replace(/pizza/gi, '🍕') });
      return next.handle(duplicate);
    }
    return next.handle(req);
  }
}
Creative Commons License