I'm curious about the reasoning or discussion that lead to the angular 2 http
service returning an observable instead of a promise for the response. I would understand the logic for something like a web socket connection or long-polling request, but the http
service simply creates an XMLHttpRequest
, and in the load
event handler for the request, emits the response on the response observable and then completes the observable. Since this only returns one value, it seems to me like a promise would make more sense.
Edit: I am aware of the difference between observables and promises, and know that you can convert observables to promises and vice versa. My question is more about the reasoning behind the decision to return an observable instead of a promise.
The biggest difference is that Promises won't change their value once they have been fulfilled. They can only emit (reject, resolve) a single value. On the other hand, observables can emit multiple results. The subscriber will be receiving results until the observer is completed or unsubscribed from.
Often Observable is preferred over Promise because it provides the features of Promise and more. With Observable it doesn't matter if you want to handle 0, 1, or multiple events. You can utilize the same API in each case. Observable also has the advantage over Promise to be cancellable.
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.
Since the get method of HttpClient returns an observable, we use the toPromise() method to convert the observable to a promise. Since you can convert an observable to a promise, you can make use of the async/await syntax in your Angular code.
I think the main reason was that observables can be cancelled.
See also Angular - Promise vs Observable.
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