需要手動unsubscribe的情況:
表單、路由、Renderer服務、infinite observable (如interval建立的)、redux中的store。
不需要手動unsubscribe的情況:
async pipe、HostListener、finite observable (如timer建立的和服務中建立的)。
取消訂閱的小技巧:使用takeUntil
export class TestComponent {
constructor(private store: Store) { }
private componetDestroyed: Subject = new Subject();
todos: Subscription;
ngOnInit() {
this.todos = this.store.select('todos')
.takeUntil(this.componetDestroyed).subscribe(console.log);
}
ngOnDestroy() {
this.componetDestroyed.next();
this.componetDestroyed.unsubscribe();
}
}