Top 10 ways to use Interceptors in Angular
Find out which interceptor superpowers you can start using today
--
There are many ways to use an interceptor, and I’m sure most of us have only scratched the surface. In this article, I will present my ten favorite ways to use interceptors in Angular.
I have kept the examples as short as possible. And I’m hoping they will inspire you to think of new ways to use interceptors. This article is not about teaching interceptors as there are already so many good articles out there. But let’s start with a little bit of basic knowledge before we start the count down.
Interceptors 101
HttpInterceptor was introduced with Angular 4.3. It provides a way to intercept HTTP requests and responses to transform or handle them before passing them along.
Although interceptors are capable of mutating requests and responses, the
HttpRequest
andHttpResponse
instance properties areread-only
, rendering them largely immutable. — Angular Docs
This is because we might want to retry a request if it does not succeed at first. And immutability ensures that the interceptor chain can re-process the same request multiple times.
You can use multiple interceptors but keep this in mind:
Angular applies interceptors in the order that you provide them. If you provide interceptors A, then B, then C, requests will flow in A->B->C, and responses will flow out C->B->A.
You cannot change the order or remove interceptors later. If you need to enable and disable an interceptor dynamically, you’ll have to build that capability into the interceptor itself. — Angular Docs
In the example app, we have all the interceptors provided, but we only use one at a time. This is done by checking the path. If it is not the request we are looking for, we can pass it on to the next interceptor with next.handle(req).
Another nice thing about interceptors is that they can process the request and response together. This gives us some nice possibilities as we will see.
For more in-depth knowledge check out this excellent article by Max Koretskyi aka Wizard: