As per https://angular.io/tutorial/toh-pt6
In general, an observable can return multiple values over time. An observable from HttpClient always emits a single value and then completes, never to emit again.
Which is indeed true, Http request/response can't produce any more values once the request completes. So what is the main reason HTTPClient returns an Observable while making a request ? Is it simply because we can apply huge set of operators on Observable (retry, debounce and so on) ? or Is there any other specific reason I am missing ?
The HttpClient service makes use of observables for all transactions.
In the case of the Angular HTTPClient module, the returned observables always emit one value and then complete (unless they error out), so this is why the situation above would not happen using HTTP Client Observables.
Angular makes use of observables as an interface to handle a variety of common asynchronous operations. For example: The HTTP module uses observables to handle AJAX requests and responses. The Router and Forms modules use observables to listen for and respond to user-input events.
Observe Response HttpClient object allows accessing complete response, including headers. In the browser, response body is a JSON object, which can be copied to a typescript interface or class type.
The best answer you'll find is Pascal Precth's one who explained that on a dedicated issue asked in December 2015: "Do Observables make sense for http?" (but feel free to read along, plenty of additional answers are really good too!)
On top of my head:
- Retry
- Cancel
- Enjoy all the Rxjs operators
- Possibility to combine them as streams
- Thinking reactively in your whole app
- Consistency
- Observables are cold by nature, no need to wrap them like Promises into a factory function if you want to trigger it later
Observables are the standard async handlers in the Angular framework.
By standard, I mean that observables are supported by the async pipe, routing guards, routing resolvers, component event emitters and many other places.
The Angular team has put in a lot of effort to support promises as a fallback for a lot of those features, but under the hood those promises are just converted to observables anyway.
By making Http requests observables the Angular team is making async operations in the core consistent with everything elsewhere.
There are still some advantages of observables over promises, but this is primarily opinniated (as in my own opinions).
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