Search code examples
javascriptangulartypescriptangular2-services

Angular 2 lazy loaded module - service not singleton


I have implemented lazy loading modules into my application, the app.module.ts is configured correctly.

@NgModule({
  declarations: [
    AppComponent,
    HeaderComponent,
    HomeComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule,
    routing
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

The routing configuration

const APP_ROUTES: Routes = [
  { path: '', component: HomeComponent },
  { path: 'tools', loadChildren: 'app/tools/tools.module#ToolsModule' }
];

export const routing = RouterModule.forRoot(APP_ROUTES);

Providing a service through the providers field in the child module and switching between components of that module reinstantiates that service (tested by logging in the service constructor).

The service is provided in the module only.

@NgModule({
  declarations: [
    ToolsComponent,
    ToolsCartComponent,
    ToolsContainerComponent,
    ToolsFormComponent
  ],
  imports: [
    CommonModule,
    toolsRouting
  ],
  providers: [ToolsService]
})
export class ToolsModule { }

Why isn't the provided service not a singleton?

EDIT:

I have modified a plunker example for lazy loading modules by adding a service scoped only to that module (backend module in this case). Switching between BackendComponent and BackendSecondComponent (which are both declared under the lazy loaded module) the service gets reinstantiated (visible in the console)

Plunker link


Solution

  • I believe this is a known issue, tracked here https://github.com/angular/angular/issues/12869.