An interceptor is a piece of code that can be executed between your HTTP calls and the rest of the application. It can be hooked up when you are about to send a request as well as when receiving a response. So, what do we use it for? There many areas of application, but some might be:
- Adding a custom token for all outgoing requests
- Wrapping all incoming error responses in a business exception; this can also be done on the backend
- Redirecting a request somewhere else
An HttpInterceptor is an interface imported from @angular/common/http. To create an interceptor, you need to take the following steps:
- Import and implement the HttpInterceptor interface
- Register the interceptor in the root module provider
- Write the business logic for what is to happen to the request