Angular の DestroyRef プロバイダーについて理解する

Mar 07 2023
Angular v16 では、DestroyRef と呼ばれる新しいプロバイダーが導入されました。これにより、特定のライフサイクル スコープの破棄コールバックを登録できるようになります。この機能は、コンポーネント、ディレクティブ、パイプ、埋め込みビュー、およびEnvironmentInjectorのインスタンスに適用できます。

Angular v16では、 と呼ばれる新しいプロバイダーが導入されましたDestroyRef。これにより、特定のライフサイクル スコープの破棄コールバックを登録できるようになります。この機能は、コンポーネント、ディレクティブ、パイプ、埋め込みビュー、および のインスタンスに適用できますEnvironmentInjector。

の使い方はDestroyRef簡単です。次のようにDestroyRefプロバイダーを挿入してコールバックを登録できます。destroy

@Component({
  selector: 'foo',
  standalone: true,
  template: '',
})
class FooComponent {
  constructor() {
    inject(DestroyRef).onDestroy(() => {
      // do something when the component is destroyed
    })
  }
}

を使用すると、 が破棄されたときに継承を必要とせずにDestroyRef必要なクリーンアップ タスクを実行する再利用可能なロジックを作成できます。これにより、実装プロセスが簡素化され、複雑さが軽減されます。scope

たとえば、以下untilDestroyedに依存する演算子を作成できますDestroyRef。

export function untilDestroyed() {
  const subject = new Subject();

  inject(DestroyRef).onDestroy(() => {
    subject.next(true);
    subject.complete();
  });

  return <T>() => takeUntil<T>(subject.asObservable());
}
@Directive({
  selector: '[appFoo]',
  standalone: true,
})
export class FooDirective {
  private untilDestroyed = untilDestroyed();

  ngOnInit() {
    interval(1000)
      .pipe(this.untilDestroyed())
      .subscribe(console.log);
  }
}