Angular’s HttpInterceptor
s 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 HttpInterceptor
s in an Angular project.
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:
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 => {
if (evt instanceof HttpResponse) {
console.log('---> status:', evt.status);
console.log('---> 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:
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';
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.
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.
Alligator.io is a developer-focused resource that offers tutorials and insights on a wide range of modern front-end technologies, including Angular 2+, Vue.js, React, TypeScript, Ionic, and JavaScript.
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!
Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.
Full documentation for every DigitalOcean product.
The Wave has everything you need to know about building a business, from raising funding to marketing your product.
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
Scale up as you grow — whether you're running one virtual machine or ten thousand.
Sign up and get $200 in credit for your first 60 days with DigitalOcean.*
*This promotional offer applies to new accounts only.