With the introduction of a new HttpClient in Angular 4.3, an old feature of Angular.js was re-introduced; HttpInterceptors. Interceptors are sitting between the application and the backend and allow you to transform a request coming from the application before it is actually submitted to the backend. And of course you when a response arrivers from the backend an interceptor can transform it before delivering it to your application logic.
This allows us to simplify the interaction with the backend in our Angular app and hide most of the shared logic inside an interceptor.
Let’s create a simple example that injects an OAuth token in our requests:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Injectable } from '@angular/core'; | |
import { HttpEvent, HttpInterceptor, HttpHandler, HttpRequest } from '@angular/common/http'; | |
import { Observable } from 'rxjs/observable'; | |
@Injectable() | |
export class OAuthInterceptor implements HttpInterceptor { | |
intercept (req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> { | |
const authReq = req.clone({ | |
headers: req.headers.set('Authorization', 'token <your OAuth token>') | |
}); | |
return next.handle(authReq); | |
} | |
} |
To be able to use the interceptor, you’ll have to register it:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
mport { BrowserModule } from '@angular/platform-browser'; | |
import { NgModule } from '@angular/core'; | |
import { HttpClientModule } from '@angular/common/http'; | |
import { HTTP_INTERCEPTORS } from '@angular/common/http'; | |
import { AppComponent } from './app.component'; | |
import { OAuthInterceptor } from './oauth.interceptor'; | |
@NgModule({ | |
declarations: [ | |
AppComponent | |
], | |
imports: [ | |
BrowserModule, | |
HttpClientModule | |
], | |
providers: [{ | |
provide: HTTP_INTERCEPTORS, | |
useClass: OAuthInterceptor, | |
multi: true | |
}], | |
bootstrap: [AppComponent] | |
}) | |
export class AppModule { } |