maroodb
maroodb

Reputation: 1118

How to create a singleton service in angular 5?

I have a service called MessageService, I want to make it singleton.

 @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.

Upvotes: 0

Views: 1110

Answers (1)

Hiren Shah
Hiren Shah

Reputation: 326

Try to provide service at module level (app.module.ts etc) and not at the component level.

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

Also make sure that this module that provides service is not lazy loaded module.

Upvotes: 1

Related Questions