首页 文章

对于http调用,Angular 2订阅/取消订阅Observable

提问于
浏览
2

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

我也知道我们可以获得对订阅的引用,并通过在订阅上调用unsubscribe方法我们可以订阅 . 例如

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调用的必要条件吗?如果是,那么这种情况下的最佳做法是什么 .

例如,我们通常会通过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);

以下是否有效,是否是在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);

1 回答

  • 3

    不,没有必要取消订阅 . 简而言之,NG2将自行清理here

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

相关问题