Angular 2 — Use Your own HTTP Library
Angular is flexible enough to let you use your desired HTTP library without worrying about change detection thanks to Zone js.
So maybe for some reason:
- You don’t like the concept of observables.
- You need some abilities that the current API doesn’t support, and you want to add them without messing with the source code. ( for example HTTP interceptors ).
- You are just really really like other HTTP library.
You can use what ever you want.
My preferred library is axios. Let’s see how easy is to integrate axios with Angular.
Install axios
npm install axios --save
Import and set the dependency injection:
In our root module, we are telling the injector, when you need the Http service return the axios object. ( library )
Use the new Http service:
Our HTTP service is the axios library so we can use the axios API and thanks to Zone js our app continue to work as usual.
Let’s try to use the interceptors API:
If you open the console, you will see the config object. Nice!
You can play with the code here.
Cons to this approach:
1. You need to have your strategy to deal with testing because you are losing all the HTTP module API goodness.
2. You are using something that Angular doesn’t maintain.
That’s all!
☞ Please tap or click “︎❤” to help to promote this piece to others.