Angular 2 — Use Your own HTTP Library

Netanel Basal
Netanel Basal
Published in
2 min readNov 28, 2016

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:

  1. You don’t like the concept of observables.
  2. 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 ).
  3. 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.

--

--

Netanel Basal
Netanel Basal

Written by Netanel Basal

A FrontEnd Tech Lead, blogger, and open source maintainer. The founder of ngneat, husband and father.

Responses (9)