ngOnDestroy、DestroyRef

使用 ngOnDestroy 生命週期鉤子:

export class MyComponent implements OnInit, OnDestroy {
  private intervalId?: ReturnType<typeof setInterval>;
  
  ngOnInit(): void {
    this.intervalId = setInterval(() => {
      const rnd = Math.random(); // 0 ~ 0.99999
      // ...
    }, 3000);
  }

  ngOnDestroy(): void {
    clearInterval(this.intervalId);
  }
}

使用 DestroyRef

DestroyRef 是 Angular 14+ 提供的新特性,可以在元件的任何地方使用:

export class MyComponent {
  private destroyRef = inject(DestroyRef);
  
  ngOnInit(): void {
    const intervalId = setInterval(() => {
      const rnd = Math.random();
      // ...
    }, 3000);

    this.destroyRef.onDestroy(() => {
      clearInterval(intervalId);
    });
  }
}

DestroyRef 的使用場景

  1. 在構造函數中:

constructor() {
  const timer = setInterval(() => {
    // ...
  }, 1000);

  this.destroyRef.onDestroy(() => {
    clearInterval(timer);
  });
}
  1. 在一般方法中:

startTimer() {
  const timer = setInterval(() => {
    // ...
  }, 1000);

  this.destroyRef.onDestroy(() => {
    clearInterval(timer);
  });
}
  1. 在事件處理中:

onClick() {
  const subscription = someObservable.subscribe();
  
  this.destroyRef.onDestroy(() => {
    subscription.unsubscribe();
  });
}

DestroyRef 的優點

  1. 可以註冊多個清理函數

  2. 清理邏輯可以直接放在設置的地方,更直觀

  3. 不需要實現 OnDestroy 介面

  4. 程式碼組織更集中

  5. 可以在元件的任何生命週期階段使用

常見的清理對象:

  • 定時器(setInterval, setTimeout)

  • 訂閱(Subscriptions)

  • 事件監聽器

  • 需要手動釋放的資源

Last updated