I have watch a few courses on Angular and have found there are different ways to manage data from an Http request.
.map()
, .subscribe()
.toPromise()
, .then()
, .catch()
I have used toPromise()
in my application as I find it similar to the AngularJS Http services.
In what scenario would I need to use Observables?
The toPromise function lives on the prototype of Observable and is a util method that is used to convert an Observable into a Promise . Inside this function we subscribe to the Observable and resolve the Promise with the last emitted value - attention - when the Observable completes!
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.
Subscribe() is a method in Angular that connects the observer to observable events. Whenever any change is made in these observable, a code is executed and observes the results or changes using the subscribe method. Subscribe() is a method from the rxjs library, used internally by Angular.
If you like the reactive programming style and want to be consistent within your application to always use observables even for single events (instead of streams of events) then use observables. If that doesn't matter to you, then use toPromise()
.
One advantage of observables is, that you can cancel the request.
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