我应该何时存储Subscription实例并unsubscribe()在NgOnDestroy生命周期中调用,何时可以忽略它们?
保存所有订阅会在组件代码中引入很多混乱.
HTTP客户端指南忽略这样的订阅:
getHeroes() {
this.heroService.getHeroes()
.subscribe(
heroes => this.heroes = heroes,
error => this.errorMessage = <any>error);
}
Run Code Online (Sandbox Code Playgroud)
同时," 航线与导航指南"说:
最终,我们会在其他地方导航.路由器将从DOM中删除此组件并将其销毁.在此之前我们需要自己清理.具体来说,我们必须在Angular破坏组件之前取消订阅.如果不这样做可能会造成内存泄漏.
我们取消订阅我们
Observable的ngOnDestroy方法.
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) subscription observable rxjs angular angular-component-life-cycle
我想知道,如果在订阅之后使用.take(1)和使用.unsubscribewhen 之间的性能有任何差异unsubscribe:
var observable = Rx.Observable.interval(100);
Run Code Online (Sandbox Code Playgroud)
第一:
var subscription = observable.subscribe(function(value) {
console.log(value);
}).unsubscribe();
Run Code Online (Sandbox Code Playgroud)
第二:
var subscription = observable.take(1).subscribe(function(value) {
console.log(value);
});
Run Code Online (Sandbox Code Playgroud)
它的任何想法都会对性能产生任何不同的看法?