Http Interceptor
Interceptors allow us to intercept incoming or outgoing HTTP requests using the HttpClient. They can handle both HttpRequest as well as HttpResponse.
-
By intercepting the Http request, we can modify or change the value of the request, and
-
By intercepting the response, we can do some predefined actions on a particular status code or message.
Most interceptors transform the outgoing request before passing it to the next interceptor in the chain(if there are multiple interceptors), by calling the next.handle(transformedReq).
Sample usecases:
Add a token or some custom HTTP header for all outgoing HTTP requests
Catch HTTP responses to do some custom formatting (i.e. convert CSV to JSON) before handing the data over to your service/component
Log all HTTP activity in the console
we need to add the interceptor as an Angular Provider in the app.module.ts.
providers: [
{
provide: HTTP_INTERCEPTORS,
useClass: InterceptorService,
multi: true
}
]
Example:
import { Injectable } from '@angular/core';
import { HttpInterceptor } from '@angular/common/http';
import { HttpRequest } from '@angular/common/http';
import { Observable } from 'rxjs';
import { HttpHandler } from '@angular/common/http';
import { HttpEvent } from '@angular/common/http';
import { FacadeService } from '../service/facade.service';
@Injectable({
providedIn: 'root'
})
export class InterceptorService implements HttpInterceptor {
token: string;
constructor(private facadeService: FacadeService) { }
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
this.token = this.facadeService.getUserToken();
if (this.token) {
const tokenizedReq = req.clone({ headers: req.headers.set('Authorization', 'Bearer ' + this.token) });
return next.handle(tokenizedReq);
}
return next.handle(req);
}
}