我看到了很多与 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/