Angular 2 在 http 调用的情况下订阅/取消订阅 Observables

Angular 2 Subscribe / Unsubscribe Observables in case of http calls

我最近才知道我们必须在 Angular 销毁组件之前取消订阅,否则可能会造成内存泄漏。

我也知道我们可以获得对订阅的引用,并且通过调用该订阅的取消订阅方法我们可以订阅。例如

private sub: any;

ngOnInit() {
  this.sub = this.route.params.subscribe(params => {
     let id = +params['id']; // (+) converts string 'id' to a number
     this.service.getHero(id).then(hero => this.hero = hero);
   });
}


ngOnDestroy() {
  this.sub.unsubscribe();
}

在 HTTP 调用的情况下是否也有必要这样做? 如果是,那么在这种情况下的最佳做法是什么。

例如,我们通常有这样的东西通过HTTPpost一些数据

let body = JSON.stringify({ name });
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers });

this.http.post(this.heroesUrl, body, options)
                .map(this.extractData)
                .subscribe((data) => {
                 //do something with data
                })
                .catch(this.handleError);

下面的方法是否有效?在 HTTP 调用的情况下,这是取消订阅的最佳方式吗?

private sub: any;

.....
....

this.sub = this.http.post(this.heroesUrl, body, options)
                .map(this.extractData)
                .subscribe((data) => {
                 //do something with data
                 this.sub.unsubscribe();
                })
                .catch(this.handleError);

不,没有必要退订。简而言之,NG2 将自行清理 here:

    if (response.ok) {
      responseObserver.next(response);
      // TODO(gdi2290): defer complete if array buffer until done
      responseObserver.complete();
      return;
    }
    responseObserver.error(response);
  };