Is it necessary to unsubscribe from observables created by Http methods?

前端 未结 9 1865
醉酒成梦
醉酒成梦 2020-11-22 04:50

Do you need to unsubscribe from Angular 2 http calls to prevent memory leak?

 fetchFilm(index) {
        var sub = this._http.get(`http://example.com`)
              


        
9条回答
  •  感动是毒
    2020-11-22 05:18

    Calling the unsubscribe method is rather to cancel an in-progress HTTP request since this method calls the abort one on the underlying XHR object and remove listeners on the load and error events:

    // From the XHRConnection class
    return () => {
      _xhr.removeEventListener('load', onLoad);
      _xhr.removeEventListener('error', onError);
      _xhr.abort();
    };
    

    That said, unsubscribe removes listeners... So it could be a good idea but I don't think that it's necessary for a single request ;-)

    Hope it helps you, Thierry

提交回复
热议问题