angular - 如何正确使用OnDestroy

标签 angular optimization memory-leaks ondestroy lifecycle-hook

我看到了很多与 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);
  }
}

关于angular - 如何正确使用OnDestroy,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54474364/

相关文章:

c - GCC 4.7.2 优化问题

ios - 分析 iPad 项目的内存泄漏

c++ - 调用 std::vector<Class type> 的析构函数使 for_each 无效

Android:Volley JsonRequest 将整个对象保留在内存中

javascript - 使用 Typescript 时在外部库中使用公共(public)变量和接口(interface)

angular - 我怎样才能让 fluent-ffmpeg 在 Angular 8 中工作

angular - 如何断点和调试 Angular 模板?

ios - 使用脏矩形优化 OpenGL ES 2.0 2D 绘图

scala - Spark : sc. WholeTextFiles 执行时间过长

html - 使用 CSS 居中和裁剪图像