Implementing HTTP interceptor in Angular2
Currently Angular2 have no implementation (yet) on interceptors. One way to achieve that is by extending
BaseRequestOptionsor any of the other involved classes in TypeScript.
What are interceptors?
Angular’s HTTP service allows us to communicate with a backend and make HTTP requests. There are cases where we want to capture every request and manipulate it before sending it to the server. Other times we would like to capture the response and process it before completing the call. Global http error handling can be also a good example of such need.
So, Interceptors are created exactly for such cases.
Let’s see what we wan’t to achieve with out Http Interceptor.
Suppose we are implementing a basic authentication on our backend server. And we want every http request to contain a secret set under
Authorisation key. That request should look something like that in below image.
Also we would like our service to prefix api url from the environment to these http requests.
Let’s build our Interceptor
First create a service. I’m naming it as
HttpInterceptor . We can other inject a
NotificationSerivce like in this example.
http GET method
Let’s add the http GET method, with some request manipulation methods.
Putting some icing on cake
Some additional methods to handle events like(success, error etc.). The
notify service can implement some
store dispatching methods in order to show
Adding to Main Module
Now that we know how to create an
http interceptor. Let’s add it to providers.
If this syntax is new to you, then go through this blog, if you want to know about dependency injection. A useful information from thoughtram.
Using it is just like using the http service in our data services.
This is how our HttpInterceptor looks like.
Notice the comments before the method implementation. These comments help us to show the method signature, whenever we are using them. So its best practice to add comments before methods.
Ohh !! Too much Code. (Try Ng2-Restangular)
This project is the follow-up of the Restangular. Ng2-Restangular is an Angular 2 service that simplifies common GET, POST, DELETE, and UPDATE requests with a minimum of client code. It’s a perfect fit for any WebApp that consumes data from a RESTful API. Live Demo on Plunkr Hero App
In this article I explained about Angular interceptors. I also provided useful examples that can help you in your development.
I hope you enjoyed reading this article as much as I enjoyed writing it!