简体   繁体   English

如何在角度5中创建单例服务?

[英]How to create a singleton service in angular 5?

I have a service called MessageService, I want to make it singleton. 我有一个名为MessageService的服务,我想使其成为单例。

 @Injectable()
  export class MessageService {
  name: string ;
  constructor() { 
     this.name = "Marouen"; 
   }

}

but I realize that every time the service is called from a component it create a new instance. 但是我意识到,每次从组件调用服务时,它都会创建一个新实例。

Try to provide service at module level (app.module.ts etc) and not at the component level. 尝试在模块级别(app.module.ts等)而不是组件级别提供服务。

@NgModule({
  declarations: [...],
  providers: [MessageService]
})
export class AppModule { }

Also make sure that this module that provides service is not lazy loaded module. 还要确保此提供服务的模块不是延迟加载的模块。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM