I've been implementing a new app in Angular 8 which uses lazy loading. However, I've hit an issue I didn't realise existed until now. That is, services loaded in a lazy loaded module creates it's own instance of that service. If I have two lazy loaded modules using the same service, then that service is loaded twice. I have read through a number of issues on stack overflow, including this one: How do I provide a service in a lazy-loaded module and have that service scoped to just the lazy-loaded module and its components?.
I'm hoping someone might be able to help me with my particular requirement / implementation.
I have an app that's split screen.
- Screen One = Component A & Component B
- Screen Two = Component B & Component C
- Screen Three = Component C & many others
In my app-routing.module.ts, I lazy load a screen-one.module
& screen-two.module
{ path: 'folders', loadChildren: '../app/screens/screen-one/screen-one.module#ScreenOneModule' },
{ path: 'folders/:folderID/projects/:projectID', loadChildren: '../app/screens/screen-two/screen-two.module#ScreenTwoModule' }
screen-one.module.ts
In this module i import two other modules (folders, projects-lists) which contain the components I need to use in the screen-one.component.html
and are displayed as <app-folders></app-folders>
& <app-projects></app-projects>
const routes: Routes = [
{
path: '',
component: ScreenOneComponent,
children: [
{
path: ':folderID/projects',
component: ScreenOneComponent,
}
]
},
]
@NgModule({
declarations: [
ScreenOneComponent
],
imports: [
CommonModule,
RouterModule.forChild(routes),
FoldersModule,
ProjectsListModule
],
})
The issue I'm having is that I have a similar set up for the screen-two.module
where I import ProjectsListModule
and ProjectDetailModule
.
The issue I'm having is, when using the FoldersService
and ProjectsListService
, the screen-one.module
loads them, and when navigating to screen-two.module
, another instance is injected again.
There might be scenarios where a total of 3 or 4 screen modules out of 10 will need access to these services.
- Is it worth putting ALL services at the app.module level?
- Or is there a way to include services in each module and not have them injected each time a new lazy loaded module is loaded?
UPDATE
I've removed any providers associated to the ProjectsListModule
and ProjectDetailModule
and relied purely on the services forRoot
functionality. However, what this currently means is that if I'm on screen 10, then I'll have services querying a database when it's not required. Not sure how to get around this when one of the services querying a database will be needed by about 3 different modules. I'd like it to be used by only those 3 modules, but for it not to have 3 instances.