Angular: HttpContextToken — Handling HTTP Requests | by Anton Marinenko | Mar, 2022

Very often within the software, we have to deal with some http requests with totally different situations. And people situations trigger totally different logic in code.

Normally, in Angular, we do that in a category that implements the HttpInterceptor interface. In fact, there are a lot of customary practices with service injection and conditional checks. However we will additionally use the energy of Angular. Let’s use HttpContextToken.

The aim of HttpContextToken reveals in its title, — this token lets you add extra information to the request context.

Let’s say we’ve an software with server requests with authorization rights. And if we don’t have rights, the request isn’t gonna be despatched. But additionally we’ve to handle requests to a number of APIs which can be open and don’t require an authorization verify.

One solution to clear up that drawback is to have a listing of open APIs and verify each request URL to be included on this listing. However that’s somewhat overhead there, let’s clear up this drawback with HttpContextToken.

We now have quite simple ApiInterceptor class with a dumb rights verify:

And here’s a service with requests:

Now we have to modify our code with HttpContextToken. For that motive let’s create an occasion of HttpContextToken token with default worth false and use it contained in the interceptor class.

With code request.context.get you will get params of the context. So, we did the primary step — add a verify for open APIs within the requests.

Now, if OPEN_API_HTTP_TOKEN token worth is true, request will probably be invoked.

Let’s take the final step and modify our service by setting the token:

That’s it! Now our software is able to work with open APIs.

Hope you loved this lesson, thanks, and stick with Angular.

More Posts