Tutorial

Angular HttpClient: Interceptors

Published on July 20, 2017
author

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 our products

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!

Become a contributor for community

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

DigitalOcean Documentation

Full documentation for every DigitalOcean product.

Resources for startups and SMBs

The Wave has everything you need to know about building a business, from raising funding to marketing your product.

Get our newsletter

Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.

New accounts only. By submitting your email you agree to our Privacy Policy

The developer cloud

Scale up as you grow — whether you're running one virtual machine or ten thousand.

Get started for free

Sign up and get $200 in credit for your first 60 days with DigitalOcean.*

*This promotional offer applies to new accounts only.