angular2 rxjs 取消訂閱的最佳實踐

    對於非一次性的Observable的訂閱,是需要釋放的(模板html的async除外),最佳實踐是創建一個BaseComponent,爲所有子類組件提供一個ngDestroyed$ Subject,在 ngOnDestroy() 勾子函數中執行next, complete,子類組件中只需takeUntil(ngDestroyed$)。

    BaseComponent

import { OnDestroy } from '@angular/core';
import { Subject } from 'rxjs';

export class BaseComponent implements OnDestroy {
    ngDestroyed$ = new Subject<void>();
   
    ngOnDestroy(): void {
      this.ngDestroyed$.next();
      this.ngDestroyed$.complete();
    }   
  }

    調用示例

import { Component, OnInit } from '@angular/core';
import { takeUntil } from 'rxjs/operators';
import { BaseComponent } from '../base.component';


@Component({
  selector: 'app-child',
  templateUrl: './child.component.html',
  styleUrls: ['./child.component.css']
})
export class ChildComponent extends BaseComponent implements OnInit{
  constructor() {
    super();
  }

  ngOnInit() {
    onStartInterval();
  }

  onStartInterval() {
    Observable
    .interval(250)
    .takeUntil(this.ngDestroyed$)
    .subscribe(val => {
      console.log('Current value:', val);
    });
  }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章