【发布时间】:2016-10-27 16:02:36
【问题描述】:
我最近知道我们必须在 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);
【问题讨论】: