Why should I use HttpClient over fetch?

2019-05-04 12:18发布

问题:

Angular 2+ introduces HttpClient which makes an HTTP request and sends them down an RxJS observable. My question is why would I choose to use HttpClient's API over the standard fetch for making single HTTP requests?

I'm familiar with RxJS and I understand this chart of "the four fundamental effects".

       | one        | many
-------------------------------------
sync   |  T         | Iterable<T>
async  | Promise<T> | Observable<T>

Http requests are async and return one value. Why should that be a Observable? I understand wanting to compose a stream of events into a stream of HTTP requests but I don't understand why I would want to use a stream of just one HTTP response. Isn't that just like using an array when you only have one value?

Am I missing something? In general, why should I use Angular's HttpClient? Where does fetch fall short?

回答1:

It's just a different API. Observables have a better way to separate "how things flow" (all operators: map, merge, concat, etc.) vs executing that (.subscribe), which often helps to get a better picture. Plus provides useful methods for cancelling or retrying a request if it fails.

And you can always use Observable.toPromise() if you need the Promise API (to use async/await, which is really useful as well)

So for me it's just two ways of representing the same thing, each one has its advantatges over the other, but as Observable is more generic they used that - You can convert back and forth from Observable to Promise, but Observables bring features that Promises doesn't have.