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?
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 firstValueFrom(observeable)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With