What Are Http Interceptors And How to Use Them In Angular?

Use cases where we can make use of Interceptors in Angular.

Vinesh
Javarevisited

--

We have faced multiple scenarios where we might want to globally capture or change every request or response, like append a user’s token or handle errors from the response and we can achieve this using Http Interceptor. Interceptor is a special Angular Service that can be used to intercept all the request and response calls and modify them to our requirement.

What Are Interceptors?

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).

We can transform the response stream by applying additional RxJS operators on the stream returned by the next.handle().

How To Create An Interceptor?

--

--

Vinesh
Javarevisited

Coder 👨‍💻, Gamer🎮 and a dog person🐶. That says a lot about me, I guess😛.