I've gone through the docs and it says/recommends to put the services under the CoreModule
if they are going to be used throughout the app and not to include services under the SharedModule
because some unexpected results could occur in case it's imported in the lazy-loaded modules. So I was going to follow the guide but I encountered some articles which say it is okay to keep services under the SharedModule
and just import it in the AppModule
with the static forRoot
method. I get what the approach tries to say but I don't understand what is better in this approach. Are there any pros and cons in both approaches? Or can I just go for the CoreModule
approach as guided in the docs?
Services by default are a singleton, i.e if you provide the service in a parent module and two child components are using same, any changes in the service will be updated in both the components, assuming you have provided service in the module and in the component as well, two instances of services will be created, so services used in both components will be different.
So, Coming back to your question, the ideal place to provide a service will be the module consuming it or the root module.
Don't provide services in the shared module, the reason it is recommended to add services to the core module is that you always import the core module in the root module, so have access to the same service throughout the application.
Providing service in submodule or at component level may cause unexpected errors if you don't know how they work under the hood, so keeping it simple you can provide the services at the root-level (won't cause any issues in lazy loading as well).
P.s you can write service anywhere just in the application just add root to its decorator.
@Injectable({
providedIn: 'root'
})
It won't matter where ever you write them as only one instance of service will be created.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With