你可能知道当你订阅 Observable 对象或设置事件监听时,在某个时间点,你需要执行取消订阅操作,进而释放操作系统的内存。否则,你的应用程序可能会出现内存泄露。
接下来让我们看一下,需要在 ngOnDestroy 生命周期钩子中,手动执行取消订阅操作的一些常见场景。
手动释放资源场景
表单
export class TestComponent {
ngOnInit() {
this.form = new FormGroup({...});
// 监听表单值的变化
this.valueChanges = this.form.valueChanges.subscribe(console.log);
// 监听表单状态的变化
this.statusChanges = this.form.statusChanges.subscribe(console.log);
}
ngOnDestroy() {
this.valueChanges.unsubscribe();
this.statusChanges.unsubscribe();
}
}
以上方案也适用于其它的表单控件。
路由
export class TestComponent {
constructor(private route: ActivatedRoute, private router: Router) { }
ngOnInit() {
this.route.params.subscribe(console.log);
this.route.queryParams.subscribe(console.log);
this.route.fragment.subscribe(console.log);
this.route.data.subscribe(console.log);
this.route.url.subscribe(console.log);
this.router.events.subscribe(console.log);
}
ngOnDestroy() {
// 手动执行取消订阅的操作
}
}
Renderer 服务
export class TestComponent {
constructor(
private renderer: Renderer2,
private element : ElementRef) { }
ngOnInit() {
this.click = this.renderer
.listen(this.element.nativeElement, "click", handler);
}
ngOnDestroy() {
this.click.unsubscribe();
}
}
Infinite Observables
当你使用 interval() 或 fromEvent() 操作符时,你创建的是一个无限的 Observable 对象。这样的话,当我们不再需要使用它们的时候,就需要取消订阅,手动释放资源。
export class TestComponent {
constructor(private element : ElementRef) { }
interval: Subscription;
click: Subscription;
ngOnInit() {
this.interval = Observable.interval(1000).subscribe(console.log);
this.click = Observable.fromEvent(this.element.nativeElement, 'click')
.subscribe(console.log);
}
ngOnDestroy() {
this.interval.unsubscribe();
this.click.unsubscribe();
}
}
Redux Store
export class TestComponent {
constructor(private store: Store) { }
todos: Subscription;
ngOnInit() {
/**
* select(key : string) {
* return this.map(state => state[key]).distinctUntilChanged();
* }
*/
this.todos = this.store.select('todos').subscribe(console.log);
}
ngOnDestroy() {
this.todos.unsubscribe();
}
}
无需手动释放资源场景
