如何正确使用OnDestroy

How to use OnDestroy properly

我看到了很多与 ngOnDestroy 相关的问题。我认为我们中的许多人没有正确使用它或根本没有使用它。
我只是想看看如何正确使用 ngOnDestroy 的提示列表,以及在最佳情况下我们应该做什么来防止内存泄漏、加速和优化 Web 应用程序。
在使用过程中,你在每种情况下都必须做什么?(你必须采取的步骤是什么?)
想要做到完美,你需要走多远?取消所有引用等

ngDestroy 在组件的实例最终被销毁之前在组件的生命周期中被调用。这是清洁组件的理想场所

import {OnDestroy } from '@angular/core'; // import from core
@Directive({
   selector: '[destroyDirective]'
 })
export class OnDestroyDirective implements OnDestroy { // implements OnDestroy

  //Call Constructor and set hello Msg.
  constructor() {
     this.helloMsg = window.setInterval(() => alert('Hello, I am Anil'), 2000);
  }

  //Destroy to the component
  ngOnDestroy() { 
      window.clearInterval(this.helloMsg);
  }
}

一个场景,您使用 Observable 并在组件中订阅它并获取数据流,即 Firebase。您应该使用 ngOnDestroy 并在离开页面时取消订阅以防止内存泄漏。

ngOnDestroy() {
  this.data.unsubscribe();
}