Angular中subscribe需要手動取消的場景

  1. Router
    Angular在組件銷燬時並沒有取消router的所有訂閱事件,同樣是延遲10秒,可以看到請求依然是會發出的。’
ngOnInit() {
    this.subscription = this.router.queryParamMap.delay(10000).subscribe((param) => {
      this.user.getUser(+param.get(id))
    })
  }

  ngOnDestroy() {
    this.subscription.unsubscribe()
  }
  1. Forms
    表單中的valueChanges和statusChanges等Observable都需要手動取消。
 ngOnInit() {
    this.form = new FormGroup({...})
    this.subscription = this.form.valueChanges.subscribe(() => {
    })
  }

  ngOnDestroy() {
    this.subscription.unsubscribe()
  }
  1. Renderer Service
constructor(private renderer: Renderer2, private element: ElementRef) {
  }

  ngOnInit() {
    this.subscription = this.renderer.listen(this.element.nativeElement, 'click', () => {
    })
  }

  ngOnDestroy() {
    this.subscription.unsubscribe()
  }
  1. 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
  }
  1. 自定義Observable
    所有自定義Observable必須在組件銷燬前手動取消。
    原文地址:Angular4最佳實踐之unsubscribe
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章