Angular 2+引入了HttpClient,它发出HTTP请求并将其发送到可观察到的RxJS.我的问题是,为什么我会选择使用 HttpClient的API 而不是标准的 fetch 用于发出单个HTTP请求?
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?
我熟悉RxJS,并且了解这张四个基本影响"的图表
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请求是异步的,并返回一个值.为什么那应该是可观察的?我知道想将事件流组合成HTTP 请求流,但是我不明白为什么我只想使用一个HTTP response 流.难道就不像只有一个值时使用数组吗?
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?
我错过了什么吗?通常,为什么要使用Angular的HttpClient?哪里不符合条件?
Am I missing something? In general, why should I use Angular's HttpClient? Where does fetch fall short?
推荐答案这只是一个不同的API.可观察对象有一种更好的方法来分离事物如何流动"(所有运算符:映射,合并,合并等)与执行该方法(.subscribe)相比,这通常有助于获得更好的画面.如果失败,Plus会提供有用的方法来取消或重试该请求.
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.
如果需要Promise API(使用async/await,它也非常有用),则可以始终使用Observable.toPromise()
And you can always use Observable.toPromise() if you need the Promise API (to use async/await, which is really useful as well)
所以对我来说,这只是两种表示同一事物的方法,每种方法都具有另一种优势,但是由于Observable更通用,因此可以使用-您可以从Observable到Promise来回转换,但是Observables带来了很多功能承诺没有的.
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.
更多推荐
为什么我应该在获取时使用HttpClient?
发布评论