首页 > 解决方案 > 当我们在服务中使用 ngOnInit 时?

问题描述

当我们在服务中使用 ngOnInit 时?

例如,我需要在服务中监听 Observer:

this.eventService.subscribe((data) => {

});

将此代码放在构造函数或 ngOnInit 中哪个更好?

标签: angularangular6angular8

解决方案


ngOnInit是一个角度生命周期钩子。它们仅在组件/指令中可用。在服务中,您不能使用它们。所以需要在构造函数下使用this。

constructor(){

  this.eventService.subscribe((data) => {

  });

}

推荐阅读