Javatpoint Logo
Javatpoint Logo

Angular Http Interceptor

It Intercepts and handles an HttpRequest or HttpResponse.

Most interceptors convert the outgoing request before passing it on to the next interceptor in the chain. Handle (transformed rake). An interceptor can also alter the response event stream by applying additional RxJS operators to the stream returned by the next.take care ().

An interceptor may rarely fully handle the request and create a new event stream instead of invoking nextHandle(). This is acceptable behavior, but be aware that further interceptors will be skipped altogether.

It is rare but valid for an interceptor to return multiple responses on the event stream for a single request.

Methods

Parameters

req HttpRequest The outgoing request object to handle.

next HttpHandler The next interceptor in the chain, or the backend if no interceptors remain in the chain.

Returns

Observable<Http Event<any>>: An observable of the event stream.

Usage notes

To use the same instance of HttpInterceptors for the entire app, just import the HttpClientModule into your AppModule, and add the interceptor to the root application injector. Suppose you import HttpClientModule multiple times in different modules (for example, in a lazy-loading module). In that case, each import creates a new copy of HttpClientModule, which overwrites the interceptors provided in the route module.

Create an Interceptor

The goal is to include the JWT that is sent to local storage as an Authorization header in any HTTP request. The first step is to build the interceptor. To do this, create an injectable class that implements HttpInterceptor.

Any interceptor we want to create needs to implement the HttpInterceptor interface. This means that our new class should have a method called intercept with parameters HttpRequest and HttpHandler. The use of interceptors transforms outgoing requests and incoming responses, but we cannot tamper with the original request - it has to be immutable. To make changes, we need to clone the original request.

As we clone the original request, we can set any header we want. In our case, it's very simple - we want to add an Authorization header with an auth scheme of Bearer after the JSON Web Token in local storage, which we get from the AuthService by calling the getToken method.

calling forward. Handle means we are passing control to the next interceptor in the chain, if there is one.

Add interceptors to providers.

The interceptor needs to be added to the HTTP_INTERCEPTORS array. This is done by converting the existing HTTP_INTERCEPTORS array using the new class we created. Add this to the ProvidersArray for our application's modules.

Any interceptor we want to create needs to implement the HttpInterceptor interface.

This means that our new class should have a method called intercept with parameters HttpRequest and HttpHandler. The use of interceptors transforms outgoing requests and incoming responses, but we cannot tamper with the original request - it has to be immutable. To make changes, we need to clone the original request.

As we clone the original request, we can set any header we want. In our case, it's very simple - we want to add an Authorization header with an auth scheme of Bearer after the JSON Web Token in local storage, which we get from the AuthService by calling the getToken method.

Add interceptors to providers.

The interceptor needs to be added to the HTTP_INTERCEPTORS array. This is done by converting the existing HTTP_INTERCEPTORS array using the new class we created. Add this to the ProvidersArray for our application's modules.

Now when we make any HTTP request, the user's token will be attached automatically.

This request will include an Authorization header with the value of Bearer I.

It should be noted that Angular's new HttpClient from @angular/common/http is being used here, not the Http class from @angular/http. If we try to request with a traditional Httpclass, the interceptor won't get hit.

Looking for unauthorized responses

When the tokens expire, we will usually get a 401 Unauthorized response from the server. This indicates that we need the user to log in again in order to get the new token.

At this time, we have a few options. Do we want to redirect to a specific route which has login form? Do we want to show a modal? Do we want to try to refresh the token?

The intercept method returns an observable, which means we can capture the success and error channels and operate on them as we wish. This is the right place to do whatever logging we want to do. We can also check for 401 Unauthorized responses and prompt the user to log in again. Either way, we need to set up interceptors to handle the responses.

This is also a great place to cache any failed requests. This comes in handy when we have token refreshing and we want to retry requests after getting a new token.

With this, we have the option of calling retryFailedRequests after refreshing the user's token to close previously failed requests. This is just a small addition that can help improve the UX, especially if you have tokens with very short lifetimes.

Wrapping Up

Angular 4.3 provides a new set of features for working with HTTP requests. Perhaps one of the most useful is the new HttpInterceptor interface that allows us to modify outgoing requests and incoming responses. This feature greatly simplifies many previously difficult tasks and removes the need for many class wrappers that have been around since the early days of Angular 2.







Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA