Search code examples
angulardependency-injectionangular-di

How to keep only one instance of service for several components?


I use DI to inject sevice in several components. Now it works not as one common instance.

How to keep only one instance of service for several components?

I trie to load service in app.module in section providers


Solution

  • If you add a provider only to @NgModule({providers: [MyService]}) (and nowhere else) then there will only be exactly one instance of MyService in your application.

    This is only true when the @NgModule() decorator is on a non-lazy loaded module. Providers of lazy-loaded modules can be imported with forRoot to ensure they will be singletons as well.

    If you add a service to @Component({ providers: [...]}), then there will be as many instances as there are instances of this component.