Why should I use HttpClient over fetch?

五迷三道 提交于 2019-12-07 03:11:22

问题


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.



来源:https://stackoverflow.com/questions/47505072/why-should-i-use-httpclient-over-fetch

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!