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.