Reputation: 155
Is there a litmus test for determining if a module is a provider or exports other modules that are providers; for determining if a module is a candidate for being listed in the "shared" module?
From angular.io:
"The SharedModule should not have providers for reasons explained previously. Nor should any of its imported or re-exported modules have providers. If you deviate from this guideline, know what you're doing and why."
https://angular.io/docs/ts/latest/cookbook/ngmodule-faq.html#!#q-module-recommendations
However if I go to use a module, let's say the ReactiveFormsModule or the RoutingModule, how do I determine if that passes the test described above? If I am only to use modules in the SharedModule that do not have providers or imported modules that re-export providers, then surely there must be some way to tell if a module meets this requirement. What is it?
Upvotes: 4
Views: 346
Reputation: 52847
Services are generally intended to be Singletons with application-wide scope.
When a module is imported, the Services provided by the imported module are added to the host module's injector. By having services within a shared module, there is a real danger of multiple modules importing the shared module and creating multiple copies of the service, each with module scope. Make sure that if you add a service to a SharedModule, that this is what you intended.
According to best practices, you should have a set of Core modules per application. These Core modules are not shared (it should only be imported by the AppModule) so it would be safe to add Services to the Core modules without breaking the Singleton intent.
The litmus test:
If you want Singleton Services that are shared application-wide, then don't put them in a SharedModule because SharedModules could be imported from multiple modules within the same application. Instead put them in CoreModules, which should only be imported by the AppModule.
Remember the following conventions and guidelines:
Upvotes: 2
Reputation: 41571
Common ways of doing things are as in the below image.
Usually providers are always listed in the providers[]
of the respective module if their scope is limited to that particular module, else move it to the Root module AppModule.
Upvotes: 1