- Router
Angular在組件銷燬時並沒有取消router的所有訂閱事件,同樣是延遲10秒,可以看到請求依然是會發出的。’
ngOnInit() {
this.subscription = this.router.queryParamMap.delay(10000).subscribe((param) => {
this.user.getUser(+param.get(id))
})
}
ngOnDestroy() {
this.subscription.unsubscribe()
}
- Forms
表單中的valueChanges和statusChanges等Observable都需要手動取消。
ngOnInit() {
this.form = new FormGroup({...})
this.subscription = this.form.valueChanges.subscribe(() => {
})
}
ngOnDestroy() {
this.subscription.unsubscribe()
}
- Renderer Service
constructor(private renderer: Renderer2, private element: ElementRef) {
}
ngOnInit() {
this.subscription = this.renderer.listen(this.element.nativeElement, 'click', () => {
})
}
ngOnDestroy() {
this.subscription.unsubscribe()
}
- fromEvent()、interval()等輸出值可能爲無限個的可觀察對象
destroy: boolean = false
ngOnInit() {
Observable.interval(1000).takeWhile(() => !this.destroy).subscribe(() => {
})
Observable.fromEvent(this.element.nativeElement, 'click').takeWhile(() => !this.destroy).subscribe(() => {
})
}
ngOnDestroy() {
this.destroy = true
}
- 自定義Observable
所有自定義Observable必須在組件銷燬前手動取消。
原文地址:Angular4最佳實踐之unsubscribe