简体   繁体   English

Angular 2延迟加载模块 - 服务不是单例

[英]Angular 2 lazy loaded module - service not singleton

I have implemented lazy loading modules into my application, the app.module.ts is configured correctly. 我已经在我的应用程序中实现了延迟加载模块,app.module.ts已正确配置。

@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). 通过子模块中的providers字段提供服务,并在该模块的组件之间切换,重新实例化该服务(通过登录服务构造函数进行测试)。

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). 我通过添加仅限于该模块的服务(在本例中为后端模块)修改了延迟加载模块的plunker示例。 Switching between BackendComponent and BackendSecondComponent (which are both declared under the lazy loaded module) the service gets reinstantiated (visible in the console) 在BackendComponent和BackendSecondComponent之间切换(它们都在延迟加载的模块下声明)服务被重新实例化(在控制台中可见)

Plunker link Plunker链接

我相信这是一个已知的问题,在这里跟踪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? 我认为这与Stackoverflow帖子的问题相同: 我如何在延迟加载的模块中提供服务,并将该服务限定为延迟加载的模块及其组件?

The solution was to create a "root component" in the lazy loaded module and add the components to this new root component. 解决方案是在延迟加载的模块中创建“根组件”,并将组件添加到此新的根组件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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