Angular 2 延迟加载模块 - 服务不是单例 [英] Angular 2 lazy loaded module - service not singleton

查看:33
本文介绍了Angular 2 延迟加载模块 - 服务不是单例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经在我的应用程序中实现了延迟加载模块,app.module.ts 配置正确.

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 { }

路由配置

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

export const routing = RouterModule.forRoot(APP_ROUTES);

通过子模块中的 providers 字段提供服务并在该模块的组件之间切换会重新实例化该服务(通过登录服务构造函数进行测试).

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?

我修改了一个延迟加载模块的 plunker 示例,方法是添加一个仅作用于该模块(在本例中为后端模块)的服务.在 BackendComponent 和 BackendSecondComponent(都在延迟加载模块下声明)之间切换,服务被重新实例化(在控制台中可见)

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 链接

推荐答案

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

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

这篇关于Angular 2 延迟加载模块 - 服务不是单例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆