Angular 2 lazy loaded module - service not singleton

孤街浪徒 提交于 2019-12-07 17:04:28

问题


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


回答1:


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




回答2:


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.



来源:https://stackoverflow.com/questions/42031521/angular-2-lazy-loaded-module-service-not-singleton

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!