简体   繁体   中英

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

我相信这是一个已知的问题,在这里跟踪https://github.com/angular/angular/issues/12869

I think this is the same problem as this Stackoverflow post: 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?

The solution was to create a "root component" in the lazy loaded module and add the components to this new root component.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM