Introduction to Angular Interceptors

Angular application uses HttpClient or Http to communicate between the API’s. Most of the latest angular applications they use HttpClient since Http is deprecated. HttpClient is more modern and easy to use than Http. So, Angular Interceptors as the name defines, they are used to intercept and modify the Http Requests globally before they sent to the respective Server.

These interceptors can perform a variety of tasks like providing authentication mechanism for all HTTP requests. So imagine without these interceptors, developers would have to implement these authentication mechanism for all the Httprequest such that it will be come very tedious.

How to create an Interceptor?

We shall see an small example of how we create an Http Interceptor in our angular application. Let’s take a scenario where you want to add some custom headers for every Http request sent by your angular application.

For creating an interceptor you need implement HttpInterceptor from @angular/common/http module.

customeHeaderInterceptor.ts

import { Injectable } from '@angular/core';
import { HttpEvent, HttpHandler, 
         HttpInterceptor, HttpRequest } 
         from '@angular/common/http';
import { Observable } from 'rxjs/Observable';

@Injectable()
export class AddCustomHeaderInterceptor 
            implements HttpInterceptor {
    intercept(req: HttpRequest<any>, 
           next: HttpHandler): Observable<HttpEvent<any>>{
        
          const modified = 
              req.clone({setHeaders: {'Custom-Header-1': '1'}});
          //adding custom header

        return next.handle(modified);
    }
}

So we have created an interceptor called customHeaderInterceptor.ts which will intercept all the Http requests and add a custom header called “Customer-Header-1″ : “1”. In the above code, we are receiving the Http request and we use req.clone to add the respective headers. Likewise you can add multiple headers you want.

app.module.ts

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

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

If you want to use this intereceptor, you need to import this interceptor in your respective module and also you need to import HTTP_INTERCEPTORS from @angular/common/http. Basically it should be mentioned in the providers section of your module.

app.component.html

 <div><h3>Response</h3>{{response|async|json}}</div>
 <button (click)="request()">Make request</button>

app.component.ts

export class AppComponent {
    response: Observable<any>;
    constructor(private http: HttpClient) {}

    request() {
        const url = 'https://jsonplaceholder.typicode.com/posts/1';
        this.response = this.http.get(url, {observe: 'body'});
    }
}

In our component, when a button is clicked we are just making an http request and we are sending the body from the component. The interceptor will intercept this request and add the respective custom header. You can able to see the customer header adding to the http request in the developer tools.

This is an simple example for an Http interceptot. But Http interceptors are mostly used for authentication. Let’s say if you want to pass an bearer authentication token based upon the logged in user for all the Http requests, Http interceptor is the right choice.

Authentication Interceptor

Let’s take a scenario where the logged in user information is stored in the local storage and you want to retrieve the respective user token from the local storage and then you have to pass this token for all Http requests.

authentication.interceptor.ts

@Injectable()
export class AuthenticationInterceptor implements HttpInterceptor {
  intercept(
    request: HttpRequest<any>, next: HttpHandler
  ) : Observable<HttpEvent<any>> {
    const userToken= localStorage.getItem('userToken');
    const copiedReq = req.clone({
      headers: req.headers.set(
        'authorization', 'Bearer ' + userToken
      )
    });    
    return next.handle(request);
  }
}

On the above authentication interceptor, you can see we are adding an userToken for all the Http requests. This is one of the major use of an Http Interceptor.

Conclusion

Http Interceptors are very much useful for multiple purposes on your angular applications. So its very much important to know this concept if know angular. And also when you want to handle some authentication mechanism in your http requests just use angular http interceptors.

In our next blog we will see how we can improve the performance of *ngFor.

Happy Coding!

Cheers! 🙂

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Blog at WordPress.com.

Up ↑

%d bloggers like this: