Anyone who has created end-to-end applications most certainly had to deal with an HTTP interceptor in angular 2.
Interceptor is a middleware and a very useful concept for handling web APIs like add a token to the header, handle different kinds of errors, redirect the specific response, start and stop loading spinner, etc.
We can simply use an interceptor in angular 2 apps, for which all we need is to extend the HTTP class and that’s it.
Create a service class and extends HTTP class, as shown in the below example-
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
import { Injectable } from '@angular/core'; import { Http, ConnectionBackend, Headers, RequestOptions, Request, Response, RequestOptionsArgs } from '@angular/http'; import { Observable } from 'rxjs/Observable'; export class InterceptorService extends Http { constructor(backend: ConnectionBackend, defaultOptions: RequestOptions) { super(backend, defaultOptions); } request(url: string | Request, options?: RequestOptionsArgs): Observable<Response> { console.log('My new request...'); return super.request(url, options); } get(url: string, options?: RequestOptionsArgs): Observable<Response> { console.log('My new get...'); return super.get(url, options); } } |
After that, you have to declare it as a provider in app
.module.ts
. Check the below code-
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { FormsModule } from '@angular/forms'; import { HttpModule,Http, XHRBackend, RequestOptions } from '@angular/http'; import { BaseRequestOptions } from '@angular/http'; import { AppComponent } from './app.component'; import { routing } from './app.routing'; import { InterceptorService} from './_services/index'; @NgModule({ imports: [ BrowserModule, FormsModule, HttpModule, routing ], declarations: [ AppComponent, ], providers: [ { provide: Http, useFactory: (backend:XHRBackend, defaultOptions:RequestOptions) => { return new InterceptorService(backend, defaultOptions); }, deps: [XHRBackend, RequestOptions] } ], bootstrap: [AppComponent] }) export class AppModule { } |
Now, every time you make an HTTP call, it logs the console before calling the base HTTP request. I have placed a console where you can place any logic you want.
You can check the demo for use of an HTTP interceptor here
If you have any queries and suggestions about HTTP interceptor using, then reach out to us in the comment box. We are the best web development providers, contact us for your project.
Share this post with your friends if you enjoyed reading it.