How to use HTTP Interceptors in Angular

In General interceptors are functions that you can execute for every request. They have extensive power to influence the content and general flow of requests and responses. Installing more than one interceptor creates an interceptor chain, in which each interceptor evaluates the request or answer before sending it on to the one after it.

How to use HTTP Interceptors in Angular
HTTP Interceptor, middleware, Programming, thetechfoyer,thetechfoyer.com

Angular Interceptor is built similarly to other services, but it must have an intercept function. You will always intercept the request and, if desired, follow it through to intercept the response.


Create A Simple HTTP Interceptor
ng generate interceptor ExampleInterceptor

With @Injectable() at the top, an angular interceptor resembles a service that implements HttpInterceptor, which provides a function called intercept that lets you intercept HTTP requests and responses.


Angular uses the intercept() function to provide a reference to the httpRequest object. If necessary, we can examine and modify this request. When our logic is finished, we use next.handle and send the revised request back to the application.


Register your intercepor in app.module
The TestInterceptor is like a 'service' managed by Angular's dependency injection (DI) system.

The interceptor class, like all other services, must be provided before the program may utilise it.
Using the HTTP_INTERCEPTORS token, we supply the HeadersInterceptor class as an interceptor in the AppModule. 
By using the multi: true option, the interceptor is added to the current array of interceptors rather than replacing them.


Parameters
req    HttpRequest, the outgoing request object to handle.
next    HttpHandler, the next interceptor in the chain, or the backend if no interceptors remain in the chain.


Operations feasible with HTTP Interceptor
Angular interceptors allow us to do a lot of different things. See Operations of HTTP Interceptor

See Also: Angular Interceptors