Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular Http - toPromise or subscribe

I have watch a few courses on Angular and have found there are different ways to manage data from an Http request.

  • Using Observables, .map(), .subscribe()
  • Using Promises, .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?

like image 830
shammelburg Avatar asked Sep 01 '16 07:09

shammelburg


People also ask

Does toPromise subscribe?

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!

Which is better Promise or Observable?

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.

Why We Use subscribe in Angular?

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.


1 Answers

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

like image 104
Günter Zöchbauer Avatar answered Sep 28 '22 01:09

Günter Zöchbauer