Let's take scenario:
App.module
|__Lazy1.module
| \__LazyService1.module
|__Lazy2.module
| \__LazyService1.module
\__(many more)
Goal is to have LazyService1.module
provide singleton instance for Lazy1/2.module
, but only be needed to be loaded when Lazy1/Lazy2 is fetched.
Angular creates and resolves root DI context only once. Any subsequent context (for lazy modules) are child contexts. My problem is that I don't want to provide services (LazyService1.module
) in App.module
(it's a big module, and only used by 2 lazy loaded ones), so logically my LazyService1.module
will NOT be resolved in root DI context.
I need to somehow share DI context between 2 lazy loaded modules, without having to make it root dependency (in App.module
).
Is there a way to define shared DI? Can one module access DI context of other?
Can lazy-loaded service be provided in root for other lazy-loaded modules to use, without providing it from root App.module
?
As for stack - I don't think I can provide a stack since I have no idea how it would look. I can implement one that eagerly provides service in root, but that is not the question here.
EDIT 2:
App.module:
@NgModule({
declarations: [
AppComponent,
],
imports: [
// Used by all:
BrowserModule,
BrowserAnimationsModule,
CommonModule,
HttpClientModule,
// App router:
AppRoutingModule
],
bootstrap: [AppComponent]
})
export class AppModule { }
Lazy-load routing module:
const routes: Routes = [
{ path: 'admin', loadChildren: () => import('./admin/admin.module').then(m => m.AdminModule) },
{ path: 'main', loadChildren: () => import('./main/main.module').then(m => m.MainModule) },
... many others, lazy or not
];
Service Module:
@NgModule({
providers: [
AuthenticationService
],
declarations: [...],
exports: [...],
imports: [
CommonModule,
]
})
export class SecurityModule { }
Service:
@Injectable()
export class AuthenticationService { ... }
And then we have those 2 lazy ones: admin
and main
.
If I were to import SecurityModule
like this:
@NgModule({
imports: [
SecurityModule
]
})
export class MainModule { }
I will end up with separate AuthenticationService
for both Main and Admin.
If I import it in App.module
, sure it works, but i have to load HUGE SecurityModule
, when it's only needed in Main/Admin which might never be accessed.