天天看点

angular何时应该手动unsubscribe

需要手动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();
 }
}