Reputation: 3175
This is very confusing in the documentation because one part suggests that loading a service in a module providers array will make it available to the whole application and if we need to isolate this service the only way is including that in the providers of a top parent component not the feature module providers.
When a module is loaded at application launch, its @NgModule.providers have application-wide scope. They are available for injection throughout the application.
Load the module lazily if you can. Angular gives a lazy-loaded module its own child injector. The module's providers are visible only within the component tree created with this injector.
If you must load the module eagerly, when the application starts, provide the service in a component instead.
https://angular.io/docs/ts/latest/cookbook/ngmodule-faq.html#!#q-component-scoped-providers
On the other hand there is another part in the docs that says otherwise and that for isolating a service we can just add it to the module's providers array and that will isolate it to this specific feature module.
The CrisisService is neither needed nor wanted outside the Crisis Center domain. Instead of registering it with the AppModule's providers — which makes it visible everywhere — we register the CrisisService in the CrisisCenterModule providers array.
This limits the scope of the CrisisService to the Crisis Center routes. No module outside of the Crisis Center can access it.
https://angular.io/docs/ts/latest/guide/router.html#!#child-routing-component
Which concept is the right one ??
Upvotes: 5
Views: 1863
Reputation: 1280
Both concepts are right. Defining a service in your NgModule causes that you can use that service as singleton.
But if you define the service into an independent component, angular will create a new instance of that service.
Upvotes: 2