Angular Http - toPromise or Subscribe

I went through several Angular courses and found that there are ways to manage data from an Http request.

  • Using Observables, .map() , .subscribe()
  • Using Promises, .toPromise() , .then() , .catch()

I used toPromise() in my application as I found it to be similar to AngularJS Http services.

In which scenario would I need to use Observables?

+15
source share
3 answers

If you like the reactive programming style and want to be consistent in your application to always use observables even for individual events (instead of event flows), then use observables. If this is not important to you, use toPromise() .

One of the benefits of being observed is that you can cancel the request.

See also Angular - Promise vs Observable

+18
source

I think that as long as the answer is not the data stream that you are going to use, you are better off using the .toPromise() approach, because it is pointless to continue listening to the answer that you do not need, and it’s not even going to change.

0
source

Default HTTP requests in angular format emit observables. It can be converted to a promise by calling toPromise (). But this is optional. Angular unsubscribes from http request as soon as it is resolved by calling

  '_xhr.removeEventListener('load', onLoad); _xhr.removeEventListener('error', onError); _xhr.abort();' 

Observables may be canceled, but promises not.

An open request remains even after the component is destroyed, which leads to a memory leak, which can be prevented by writing off the observable or by calling the destruction method as soon as the component is destroyed. Unsubscribe methods to prevent memory leaks

Conclusion: it is better to use observables with methods to prevent memory leaks.

0
source

All Articles