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 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).
- You can easily mix between Http requests and WebSockets in a service and expose the APIs as observables. The consumer of the service will not know the difference.
- You can easily convert a Http request for an array into an observable that emits each item individually. This makes dispatching data to different consumers a lot easier.
- Promises can break when they are not chained properly. These common bugs are often avoided with observables.
To maintain API consistency. No need to introduce Promises for example. Observables are more flexible than Promises anyway. Moreover observable can track its subscribers. In case of HttpClient call is made once subscribear appear. If you dont subscribe to http call, request will not be made.
That is why if you subscribe multiple times to 1 observable, multiple request will be made.
来源:https://stackoverflow.com/questions/50495701/why-angular-uses-observable-for-httpclient