我最近才知道,我们必须在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);
不需要退订。简而言之,NG2将自行清理,如下图所示:
if (response.ok) {
responseObserver.next(response);
// TODO(gdi2290): defer complete if array buffer until done
responseObserver.complete();
return;
}
responseObserver.error(response);
};