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

Nav*_*med 5 angular2-services angular

我最近了解到,我们必须在 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();
}
Run Code Online (Sandbox Code Playgroud)

在 HTTP 调用的情况下也有必要吗?如果是,那么这种情况下的最佳实践是什么。

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

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);
Run Code Online (Sandbox Code Playgroud)

下面的方法可行吗?这是在 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);
Run Code Online (Sandbox Code Playgroud)

小智 5

不,没有必要取消订阅。简而言之,NG2 将自行清理,如下所示

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

  • 如果进行了 http 调用但尚未返回并且用户离开视图,会发生什么情况?我想在这种情况下你会留下一个悬而未决的订阅? (3认同)