Angular Http - toPromise or subscribe

前端 未结 3 1879
走了就别回头了
走了就别回头了 2021-02-03 23:11

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(), .s
相关标签:
3条回答
  • 2021-02-03 23:21

    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

    0 讨论(0)
  • 2021-02-03 23:39

    I think as long as the response is not a data stream that you're going to use, then you'd better use the .toPromise() approach, because it's meaningless to keep listening to a response that you don't need and it's not even going to change.

    0 讨论(0)
  • 2021-02-03 23:45

    Default http requests in angular emits observables. It can be converted to promise by calling toPromise(). But it is not required. Angular unsubscribes the http request once it gets resolved by calling

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

    Observables are cancellable, but promises are not.

    The open request remain even after the component gets destroyed leading to memory leakage, which can be prevented by unsubscribing the observable or calling the destroy method once the component gets destroyed. Ways to unsubscribe to prevent memory leaks

    Conclusion, better to use observables with memory leak prevention techniques.

    0 讨论(0)
提交回复
热议问题