如何将 ngrx/store 功能模块与延迟加载模块一起使用?

Gre*_*nko 3 ngrx angular ngrx-store

在我的 angular 应用程序中,我有一些功能模块:

  • CoreModule(包含用于 api 调用和模型的服务)
  • MainModule(包含主应用程序的组件)
  • MainDetailModule(包含详细视图功能,延迟加载)
  • MainStoreModule(包含 ngrx/store 定义、动作、reducer 等)

main.module.ts (MainModule)

// imports

@NgModule({
  imports: [
    CommonModule,
    FormsModule,
    CoreModule,
    MainRoutingModule,
    TranslateModule.forChild(),
    BsDropdownModule.forRoot(),
    MainDetailModule,
    MainStoreModule
  ],
  declarations: [
    // components
  ],
  providers: []
})
export class MainModule { }
Run Code Online (Sandbox Code Playgroud)

main-detail.module.ts (MainDetailModule)

// imports

@NgModule({
  imports: [
    CommonModule,
    FormsModule,
    ReactiveFormsModule,
    MainDetailRoutingModule,
    TranslateModule.forChild(),
    MainStoreModule
  ],
  declarations: [
    // components
  ]
})
export class MainDetailModule { }
Run Code Online (Sandbox Code Playgroud)

main-store.module.ts (MainStoreModule)

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { StoreModule } from '@ngrx/store';
import { StoreDevtoolsModule } from '@ngrx/store-devtools';
import { metaReducers, rootReducers } from './reducer/root.reducer';

@NgModule({
  imports: [
    CommonModule,
    StoreModule.forRoot(rootReducers, {metaReducers}),
    StoreDevtoolsModule.instrument({
      maxAge: 10
    })
  ],
  declarations: []
})
export class MainStoreModule { }
Run Code Online (Sandbox Code Playgroud)

我的 MainModule 导入 CoreModule、MainStoreModule 和 MainDetailModule。MainDetailModule 将通过单击详细信息链接延迟加载。

在整个主应用程序中,我的 MainStore 工作正常。但是,如果我导航到 MainDetailModule,MainStoreModule 将被重新初始化,因此它将保持为空。我知道 ngrx/store 可以处理延迟加载的模块,我知道如何 . 我的问题是如何让我的 MainStoreModule 与我的延迟加载模块一起工作?我应该在 MainStoreModule 中实现类似 forRoot() 和 forChild() 的函数吗?

Bor*_*par 6

使用 ngrx store ( StoreModule.forFeature('feature-name', {feature-reducers}))加载延迟加载模块时,我遇到了类似的意外行为。store 被重新初始化,之前分派的所有 action 都被再次分派。

该问题已通过ngrx4.1.1o升级5.2.0


小智 5

如果您计划延迟加载 MainDetailModule,则无法在其中导入 MainStoreModule。这样做将导致它产生主商店的另一个实例。如果您只想订阅主商店并且没有任何功能级别减速器,我相信您可以按原样导入 StoreModule ie

@NgModule({
  imports: [
    CommonModule,
    FormsModule,
    ReactiveFormsModule,
    MainDetailRoutingModule,
    TranslateModule.forChild(),
    StoreModule
  ],
  declarations: [
   // components
  ]
})
export class MainDetailModule { }
Run Code Online (Sandbox Code Playgroud)

如果您有功能级别缩减器,那么您将使用

StoreModule.forFeature('feature-name', {feature-reducers})
Run Code Online (Sandbox Code Playgroud)