I've been questioning myself about the correct place to put the services that talk to API in my Angular app. Initialy, I thought the best position should be in the module of the feature but I'm having doubts about it.
Let's say I have lazy loaded module FeatureA that CRUDs a table in my database thanks to the API endpoint, so I put FeatureAService as a provider for my FeatureAModule.
But let's say that I have another lazy loaded module FeatureB that needs to read the info. I already have a function that helps me to do just that in my FeatureAService so I can reuse it, but I need to provide the service.
I could import my FeatureAModule into my FeatureBModule but I think that will also bring all the components of FeatureA. And I could put my FeatureAService in a third module shared between my FeatureA and FeatureB, but that begs the question: Should all data services be placed in said module so that they can be available throughout the application?
Normally you would want to import the service above the lazily-loaded modules so there is a singleton instance of it that any module can access. There's some odd stuff you can do with @SkipSelf
, but it's not generally considered to be best practice.
The official Angular docs advise to create services in their own feature module, and have services that should be available across the app be injected into the root module, or if there's a service that is shared across a handful of lazy loaded modules, injected into the parent of those lazily loaded modules.
So, that service should be its own module, and imported into the closest parent module that makes sense.