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 .
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.
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.
3. We can create a fake back end and mock the responses.
4. We can cache responses.
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.
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 !!!