Bypass Angular Interceptors with Request Metadata
Angular has a very powerful way of providing common logic to every http request made by your application.
With HttpInterceptor
you can add headers, log things, handle errors… Basically anything you may want to do with ALL http requests.
But sometimes you want to bypass one of your interceptors for just some requests. Up until now, you had a couple ways for doing this.
- Adding some http header in your request and inspect it in your interceptor.
- Creating a new HttpClient for your request.
- Managing your HttpClient injections with tokens.
These were all ways of trying to let your interceptor know about some special condition your request had that needed to be treated differently.
HttpContext
With Angular 12, there is a new way of passing information down to your interceptor that doesn't look like something you are ashamed of doing. =)
You can now pass metadata from your request to your interceptor using a HttpContext.
Here is your interceptor:
And here is your httpClient
request:
Notes:
- You can declare your
HttpContextToken
where you feel it makes more sense. - This token can be any kind of data. boolean, number, string, object, array...
- This context is mutable. So you can update its value during your request/response cycle.
I'm very excited to see this finally implemented in Angular! 🎉
Big thanks for everyone who worked very hard and did not lose hope to get this into the framework!