Skip to main content

Angular 2: Intercepting HTTP calls

You intercept an HTTP call when you want to make changes in the call before it can acutally leave your user's browser and take your request to the server. There are several use cases when you want to do this for example in an Angular1.2 based application we wanted to append API path prefix "api" in all calls. We used standard AngularJs $httpProvider to configure the interceptor. There are multiple other scenarios in which you may want to intercept http calls, for example:


  • Adding authentication token to every request
  • Modifying headers of each call according to your backend's needs
  • Displaying a custom loading message on each request
  • Handling API errors
You can either use already available libraries in your project to intercept calls, but if you don't want to add another external dependency in your application, follow these simple steps to add one or more http interceptors in your application.

Step 1:
Write a class that extends HttpInterceptor interface from Angular common http library.

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

@Injectable()
export class MyInterceptor implements HttpInterceptor {

  intercept(req: HttpRequest<any>, next: HttpHandler):
    Observable<HttpEvent<any>> {
    // DO something here.
    return next.handle(req);
  }
}
Step 2:
Make your angular engine aware about your newly created interceptor. Import it in your module file and add it in your providers list like the following

import { HTTP_INTERCEPTORS } from '@angular/common/http';
import { MyInterceptor } from './my-interceptor';
...
providers: [
  { provide: HTTP_INTERCEPTORS, useClass: MyInterceptor, multi: true },
]
...
That's all you have to do to intercept your calls in Angular2 application.


Order of Multiple interceptors

You can have multiple interceptors in your application and order in which you will add your interceptors in your module matters. So if you have three interceptors AuthInterceptor, PathInterceptor, LoadingInterceptor and you add them like following in your module file

import { HTTP_INTERCEPTORS } from '@angular/common/http';
import { MyInterceptor } from './my-interceptor';
...
providers: [
  { provide: HTTP_INTERCEPTORS, useClass: AuthInterceptor, multi: true },
 { provide: HTTP_INTERCEPTORS, useClass: PathInterceptor, multi: true },
{ provide: HTTP_INTERCEPTORS, useClass: LoadingInterceptor, multi: true }
],
...
They all be called in the sequence in which you have provided them in the array i.e first of all AuthInterceptor then PathInterceptor and then LoadingInterceptor and you will get response in the reverse order.

Comments

Popular posts from this blog

Html5 Canvas Drawing -- Draw dotted or dashed line

This post is for those who want to use html5 canvas for drawing. The canvas API now has built in methods to create lines with dashes. The method is called setLineDash. Following is the code sample to create dashed line. var canvas = document . getElementById ( "canvas" ); var ctx = canvas . getContext ( "2d" ); ctx . setLineDash ([ 5 , 3 ]); /*Dash width and spaces between dashes.*/ ctx . beginPath (); ctx . moveTo ( 0 , 100 ); ctx . lineTo ( 400 , 100 ); ctx . stroke (); If you want to draw lines having a custom style there is no methos in the API. But fortunately there is a way to achieve this. Following is a description about how I achieved this. You can set the stroke pattern on canvas context. Stroke pattern can be created using any image. You create image for your custom pattern and set strokeStyle of the context like the following: var linePattern; imageToUsedAsPattern.onload = function() { linePattern = context.createPattern(imageToU...

Grouping Exports in Javascript code

As a Javascript developer, you will come across many occassions when you will have to export many functions, variables or other items from one file and import them in different files. You may end up with a code like the following export const function1 = () => { /*something here */ } ; export const function2 = () => { /*something here */ } ; export const function3 = () => { /*something here */ } ; export const function4 = () => { /*something here */ } ; export const function5 = () => { /*something here */ } ; export const function6 = () => { /*something here */ } ; export const function7 = () => { /*something here */ } ; And in the file you want to import you will be importing like the following import { function1, function2, function3, function5, function6, function7 } from './path_to_the_script' You can improve it using * if you want to import all the functions. import * as Functions from './path_to_the_script' This is a better way of imp...

Angular Directives

Word Direcitve means something that serves to direct or guide towards an action or goal. The purpose of Directives is similar in Angular too. Directives are basically markers for DOM elements and are used to either create new HTML elements or extend behavior of already present elements. There are three types of Directives Component Directive Strucutral Directive Attribute Directive To create a directive in Angular2, you have to follow these steps Create a regular javascript class and decorate it with @Directive decorator import { Directive } from '@angular/core' ; @Directive ({ selector : "[disableOnClick]" , }) class DisableOnClick { @ HostListener ( 'click' , [ '$event.target' ]) onClick ( element ) { element.disabled= "disabled" } } Declare it in your module declaraion file e.g app.module.ts import { NgModule } from '@angular/core' ; import { DisbaleOnClick } from './...