Angular - where to provide services?

876 Views Asked by At

If I want to isolate service in one module, I should create one root component for module, and use providers on this component (as said docs).

If I use providers on the module, service become application level. So, it is way to provide application-level services (as it made in example).

But, at the next, docs says:

Do not specify app-wide singleton providers in a shared module. A lazy loaded module that imports that shared module will make its own copy of the service.

So, we should not use providers of the modules to provide shared services. So, what should we use? AppModule providers? Should we provide all shared services in AppModule? When we should use providers of the feature modules?

Looks like, module providers are shared, but you should not use them as shared. WTF?

2

There are 2 best solutions below

0
On BEST ANSWER

It is Angular issue, that is still open.

7
On

Do not specify app-wide singleton providers in a shared module. A lazy loaded module that imports that shared module will make its own copy of the service.

This only applies to lazy loaded modules. Providers in non-lazy loaded modules always are added to the application root scope.

Lazy loaded modules get their own root scope, because the root injector can't be modified later (after it was initialized).

To ensure that all services are provided at root level, implement the forRoot() method and provide the services there. Then import the service at the AppModule with imports: [MyModule.forRoot()]