After successfully implementing lazy loading modules into my application, I have ensured that the app.module.ts is properly configured.
@NgModule({
declarations: [
AppComponent,
HeaderComponent,
HomeComponent
],
imports: [
BrowserModule,
FormsModule,
HttpModule,
routing
],
bootstrap: [AppComponent]
})
export class AppModule { }
The routing setup
const APP_ROUTES: Routes = [
{ path: '', component: HomeComponent },
{ path: 'tools', loadChildren: 'app/tools/tools.module#ToolsModule' }
];
export const routing = RouterModule.forRoot(APP_ROUTES);
One observation is that providing a service through the providers field in the child module and switching between components of that module causes the service to be reinstantiated (confirmed through logging in the service constructor).
The service is only provided within the module.
@NgModule({
declarations: [
ToolsComponent,
ToolsCartComponent,
ToolsContainerComponent,
ToolsFormComponent
],
imports: [
CommonModule,
toolsRouting
],
providers: [ToolsService]
})
export class ToolsModule { }
I am puzzled as to why the provided service is not functioning as a singleton.
UPDATE:
Addition to the discussion, I have enhanced a plunker example for lazy loading modules by introducing a service scoped solely to that module (specifically in the backend module). Upon toggling between BackendComponent and BackendSecondComponent (both declared under the lazily loaded module), it is observed that the service undergoes re-instantiation (evident in the console)