/ angular

Using Angular HttpInterceptor with the new HttpClient

If you haven't seen already, a new HttpClient was shipped with Angular 4.x and this allows us to interact with the HttpInterceptor relatively easy. Why do we need it? Well, you've most likely ran into this issue before...

  • What's the best way to add an Authorization header across all my requests?
  • How can I pre/post process a HTTP request/response?
  • I want to add global error handling, logging, or some other behaviour attached to my HTTP requests.

We'll be looking at how we can best achieve these goals within this article. Let's take the GitHub API as an example.

If I wanted to GET users by a particular username, I could make a Http request like so:

// github.service.ts
import { User } from './../models/user.model';
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Injectable()
export class GitHubService {
  ROOT_URL = 'https://api.github.com';
  
  constructor(private http: HttpClient) {}

  getUserInformation(userId: string) {
    return this.http.get<User>(`${this.ROOT_URL}/users/${userId}`);
  }
}

This would work fine unauthenticated, but we'd potentially run into rate limiting issues and/or may want to do something that requires authentication. Let's look at how we can intercept this request and add an Authorization token using the HttpInterceptor.

// github.interceptor.ts
import { User } from './../models/user.model';
import { HttpInterceptor, HttpRequest } from '@angular/common/http/';
import { HttpHandler } from '@angular/common/http';

export class GitHubHttpInterceptor implements HttpInterceptor {
  intercept(req: HttpRequest<User>, next: HttpHandler) {
    const newReq = req.clone({
      headers: req.headers.set(
        'Authorization',
        'token your-auth-token'
      )
    });

    return next.handle(newReq);
  }
}

Notice how our interceptor is simply just a class that implements the HttpInterceptor interface. This is a function that takes our HttpRequest and returns a new request with the HttpHandler.handle(request) call. We're cloning the request and setting a new header, but arguably we could do anything we wanted to here.

To add this within our application, we'll need to register it within our module's providers array.

import { GitHubHttpInterceptor } from './modules/github/services/github.interceptor';
import { HTTP_INTERCEPTORS } from '@angular/common/http';

@NgModule({
  providers: [
    {
      provide: HTTP_INTERCEPTORS,
      useClass: GitHubHttpInterceptor,
      multi: true
    }
  ],
})
export class AppModule {}

The awesome thing about the new HttpClient is that we can create as many HttpInterceptors as we want. If we want to intercept multiple requests, we can set multi: true! :)

Paul Halliday

Progress Telerik Developer Expert. Course author with students in 110+ countries. BSc (Hons) Computer Science @ UoS. Google accredited Mobile Site professional.

Read More