Angular 7/6 | Handle HTTP Request and Response using Interceptors in Angular 4.3 plus versions

Angular Interceptor is a powerful feature which can be used in many ways for securing and handling many HTTP related phenomena. HTTP interceptors were available in AngularJS but were missing in Angular 2, so there was a missing gap to manipulate HTTP calls globally at one place.

In Angular 4.3 version HttpInterceptors interface was added to enable new possibilities in a real-world application.

What we can do using Interceptors?

Interceptors can be used in a number of ways in an application.

– Set request headers in HTTP calls like Content-Type or send any custom headers.

– Authenticate HTTP calls by setting Security tokens

– Show Spin Loaders/ Progress Bars as HTTPS calls are in progress.

Handle Errors in HTTP calls at one place

– Show Response messages using Notifications/ Toasts

In a nutshell, we can say whatever is possible to do with HTTP calls, can be achieved by Inceptors.

In this post, we will only discuss How to send custom Headers and handle Response and Error in HTTP Calls using Interceptors.

How to implement Angular Interceptors?

Adding Interceptors in Angular 4.3+ versions is very easy and includes very few steps. Let’s discuss implementations step by step.

Create a new project using Angular CLI (current version is 7.3.8)

Create an Interceptor

We will create a new Interceptor class named httpSetHeaders to set request headers. This will implement HttpInterceptor.

Above class implements HttpInterceptor which will call intercept method to take control of the HTTP call. Here we made changes to HTTP headers by using the clone method as we can’t make changes to read only responses and requests.

Add Interceptor in app.module.ts file

Next, we need to add created interceptor in the app’s module and also HTTP_INTERCEPTORS in providers.

Now whenever a new HTTP request will be made, this Interceptor will modify the Headers of request. We can easily handle responses and errors by calling catchError method.

 

 

 

Leave a Reply

Your email address will not be published. Required fields are marked *