Creating a HTTP Intercepter
Angular V4.4.4
We need to inherit the ‘HttpIntercepter’ class and override the ‘intercept’ method to be able to intercept all the HTTP requests you make using ‘HttpClient’.
auth-interceptor.ts
import {Injectable} from '@angular/core'; import {Observable} from 'rxjs/Observable'; // import 'rxjs/add/operator/do'; import {HttpEvent, HttpResponse, HttpInterceptor, HttpHandler, HttpRequest} from '@angular/common/http'; @Injectable() export class AuthInterceptor implements HttpInterceptor { constructor(private auth: AuthService) {} intercept(req: HttpRequest, next: HttpHandler): Observable > { // Clone the request as it is immutable. You can also save the original request in the following way // const prevReq = req.clone(); const authReq = req.clone({headers: req.headers.set('Authorization', 'Bearer ' + getToken())}); // or you can use the shorter version of the same. //const authReq = req.clone({setHeaders: {Authorization: 'Bearer ' + getToken()}}); // Pass on the cloned request instead of the original request. return next.handle(authReq); /* you can test the above function by doing a console.log() here. For this you will need to import 'HttpResponse' and the 'do' operator. .do(event => { if (event instanceof HttpResponse) { console.log(getToken()); } }); */ } }
Updating app.module.ts
Now you need to include the ‘AuthInterceptor’ class as part of our main app module providers after you have imported ‘HTTP_INTERCEPTORS’.
app.module.ts
import {NgModule} from '@angular/core'; import {AuthInterceptor} from './auth-interceptor' import {HTTP_INTERCEPTORS} from '@angular/common/http'; @NgModule({ providers: [{ provide: HTTP_INTERCEPTORS, useClass: AuthInterceptor, multi: true, }], }) export class AppModule {}