How to create HTTP Interceptor in Angular 11
Every application needs to communicate with the backend server for data to show in UI, and for that, we mostly use either JSON or XML. But for backend communication, the REST API needs to be authorized based on Authorization & Authentication (Bearer token).
Angular Interceptor helps to modify the HTTP request globally before they are sent to the server. Interceptors are a unique type of Angular Service that we can implement. Interceptors allow us to intercept incoming or outgoing HTTP requests using the HttpClient. By intercepting the HTTP request, we can modify or change the value of the request.
Interceptors is a unique type of Angular service that allow us to intercept incoming or outgoing HTTP request using HttpClient.
In this blog, we are going to discuss the following points -
- Setup and configure Interceptor
- HTTP Request & Response
- HTTP Error Handling
Setup And Configure Interceptor
First, create an Angular project, and import HTTPClientModule to the app.module.ts file. HTTP interceptor class can be created by extending HttpInterceptor. So let's create that one.
npm g service service/http-interceptor
It will create an http-interceptor service along with a unit test case file (http-interceptor.service.ts & http-interceptor.service.spec.ts). Update the file accordingly.
Update the app.module.ts file as well.
HTTP Request & Response
So in the case of the HTTP request, you might have few requests are needed a custom HTTP Header like "Authorization" and a few do not require any header. In such cases, you can have an array that defines the list of URLs that does not need any header.
Also, you can add a default timeout value for your API call. So once the expected time elapses, API will throw an error at the component, and you can handle it from there.
In case of Success response with HTTP code 200, you can send it to the component. But in the case of other HTTP error codes like 400 series, 500 series, etc you can handle it in your way.
HTTP Error 400, 404, 403 - Notify component that API failed to get a response. You can show a Toast message for that.
HTTP Error 401 - The access token has expired, you need to renew the token and call the same API once again with the renewed token.
HTTP Error 500 - Notify the component that API failed to get a response. You can show a Toast message for that.
HTTP Interceptor Service
You can find the actual codebase from here.
If you have any questions or clarification please comments below.