Tutorial

Angular HttpClient: Interceptors

Published on July 20, 2017
Default avatar

By Alligator.io

Angular HttpClient: Interceptors

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);
  }
}

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about us


About the authors
Default avatar
Alligator.io

author

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
Leave a comment


This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

Try DigitalOcean for free

Click below to sign up and get $200 of credit to try our products over 60 days!

Sign up

Join the Tech Talk
Success! Thank you! Please check your email for further details.

Please complete your information!

Get our biweekly newsletter

Sign up for Infrastructure as a Newsletter.

Hollie's Hub for Good

Working on improving health and education, reducing inequality, and spurring economic growth? We'd like to help.

Become a contributor

Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

Welcome to the developer cloud

DigitalOcean makes it simple to launch in the cloud and scale up as you grow — whether you're running one virtual machine or ten thousand.

Learn more
DigitalOcean Cloud Control Panel