【问题标题】:Is an angular service provided to a component destroyed when the component is destroyed?当组件被销毁时,提供给组件的角度服务是否被销毁?
【发布时间】:2018-08-21 22:30:43
【问题描述】:

我有一个每隔 10 秒检查一次数据状态以更新组件中的标签的服务。只有在组件所在的页面上才需要这样做。该组件看起来有点像这样:

@Component({
  selector: 'editor-status',
  templateUrl: './editorStatus.component.html',
  providers: [EditorStatusService]
})
export class EditorStatusComponent implements OnDestroy {
  constructor(private service: EditorStatusService){};
  public ngOnDestroy(): void {
    service.destroy();
  }
}

我的服务有这种结构:

@Injector()
export class EditorStatusService {
  private intervalId: any;
  constructor() {
    this.intervalId = setInterval(() => { 
      /* code to update ui */ 
    }, 10000);
  }
  public destroy(): void {
    clearInterval(this.intervalId);
  }
}

是否在每次实例化组件时都以这种方式为组件提供服务?如果我不销毁侦听器,我会在每次加载此页面然后导航离开时创建内存泄漏吗?

【问题讨论】:

    标签: angular


    【解决方案1】:

    组件提供的服务在组件被销毁时会自动销毁。

    您可以通过服务中的 ngOnDestroy 生命周期挂钩进行测试:

    ngOnDestroy(): void {
      console.log('service destroyed');
    }
    

    当组件被销毁时,它应该在控制台中写入'destroyed'。

    【讨论】:

    • 这是否包括服务中未受贿的任何订阅,或者这里是否存在潜在泄漏?
    猜你喜欢
    • 1970-01-01
    • 2011-02-23
    • 2019-01-28
    • 2019-12-04
    • 1970-01-01
    • 1970-01-01
    • 2017-07-07
    • 2018-03-23
    • 2019-04-26
    相关资源
    最近更新 更多