Angular组件变量是否应在ngOnDestroy()中设置为null?

前端之家收集整理的这篇文章主要介绍了Angular组件变量是否应在ngOnDestroy()中设置为null?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
Angular文档说

ngOnDestroy(): Cleanup just before Angular destroys the directive/component. Unsubscribe Observables and detach event handlers to avoid memory leaks.
Called just before Angular destroys the directive/component.

一些开发人员说组件属性(类变量)也应该设置为null以避免内存泄漏.这是真的?

export class TestComponent implements OnInit,OnDestroy {

  public name: string;
  constructor() { }

  ngOnInit() {
    this.name = 'John';
  }

  ngOnDestroy() {
   // is this code really necessary.
   this.name = null;
  }

}

解决方法

不,你不需要那个. Component只是一个类,当它显示时,就会创建一个实例.当组件被销毁时,关联的对象将被保留而不会被引用,并且尽快将其进行垃圾回收.

正如文档所述,您只需要在Observables和事件处理程序的情况下使用,因为如果它们处于活动状态,它们将不会被垃圾收集器删除.

Unsubscribe Observables and detach event handlers to avoid memory leaks

猜你在找的Angularjs相关文章