How to Intercept the HTTP Requests in Angular (Part 1)

Udith Gayan Indrakantha
Jan 14 · 2 min read

Content

This article consists of two parts as Part 1 and Part 2.

Part 1 -- Introduction , Some Advantages of Angular Interceptor.

Part 2 -- A Practical Explanation of Implementing Interceptor .

Introduction

Since Angular 4.3 , a new feature has been coming to modify all outgoing http requests and incoming responses globally. In other words, we can pre-process all the http requests and responses. With this new feature, an Angular developer has been enabled to reduce unnecessary efforts and do the tasks with less effort and less set of lines.

Before going to the coding and implementation part, let me list out what the http interceptors can do so that you can get a good idea why we need and where we need interceptors.

With HttpInterceptor interface,

1. You can add new headers and modify existing headers of an http request.

Learn more

2. We can retry a request several times on certain http errors.

Network errors are common and we can retry a request several times to get success.

Learn more..

3. We can create a fake back end and mock the responses.

Learn more..

4. We can cache responses.

Learn more..

5. Conversion of responses can be done.

When an API sends data in a format that we do not like, we can convert it to a format that we like, here. (ex: XML >>>> Json)

6. A Loader can be shown while fetching data.

7. We can manipulate and change URL

Let’s say, we want to change .com part of the URL into .lk due to some reason. It can be done here too.


Conclusion

Interceptors are a great facility in Angular where you can do great things with less effort without replicating your codes and create an amazing application. Everything is upto your creativity.

Let’s implement one Interceptor class and do some tricks with it. Read the next part of this article :

How to Intercept the HTTP Requests in Angular (Part 2)


Enjoy the Day !!!

JavaScript in Plain English

Learn the web's most important programming language.

 by the author.

Udith Gayan Indrakantha

Written by

Technology Enthusiast | Full Stack web Developer | https://iamudith.netlify.com

JavaScript in Plain English

Learn the web's most important programming language.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade