Every front-end application requires some kind of backend to get the data and display the same in UI and Angular which is a very popular front-end framework that also requires the backend calls to do multiple operations. In the actual real-time application we may require to edit requests like adding headers/Logs the request or response, etc...
Angular provides a feature to intercept the request/response via HttpInterceptor where we can log the request/response or add a header for all the requests going out of the front-end to the back-end.
Angular provides an interface named HttpInterceptor defined in "@angular/common/http" library of Angular in which we have an intercept method where we can intercept the request and response to customize it as per our requirement.
Suppose we want a header for every request going to the back-end and it's not feasible to do every method in Angular service which will violate code-reuse so instead we will use HttpInterceptor in Angular.
Step 1 Create a typescript file that will inherit the intercept method of HttpInterceptor as below
As you can see above we are adding isProd flag value to every request to determine whether this particular request is from the production environment or dev/local environment. Similarly, you can add any number of headers value in the requestor logs the request before hitting next.handle(authReq) line.
We can have multiple HttpInterceptor which can do multiple kinds of operations.
The above interceptor is only intercepting request but sometimes we may also require to intercept response as well and below is an example of the same.
Step 2: Configure the HttpInterceptor providers array in AppModule class
We can also use multiple Interceptor in a single application and the order of invocations will be the same as order it's mentioned in providers array in AppModule.
Hope you have enjoyed the article!
Share This Post