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

时间:2016-06-24 23:31:45

标签: angular angular2-services

我最近才知道,在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 个答案:

答案 0 :(得分:3)

不,没有必要取消订阅。简而言之,NG2将在看到here之后进行清理:

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