Angular ngrx-store : How to share store among modules (main module/feature module)

标签 angular typescript ngrx-store-4.0

我有两个 Angular 模块:mainfeature:

主/根模块:

@NgModule({
    imports: [
        StoreModule.forRoot({router: routerReducer}),
        EffectsModule.forRoot([...]),
        ...
    ],
    declarations: [],
    ...
})
export class AppModule {}

功能模块:

@NgModule({
    imports: [
        StoreModule.forFeature('feature', {someValue: someValueReducer}),
        EffectsModule.forFeature([...]),
        ...
    ],
    declarations: [],
    ...
})
export class FeatureModule {}

我需要访问主模块中的“功能”数据片段,以根据存储在 feature 模块中的数据有条件地显示/激活应用程序选项卡。

(换句话说,我需要所有模块 main 和任何 feature 模块都可以访问的全局/共享状态。)

  1. 有可能吗?
  2. 这被认为是良好的做法吗?

目前我不能这样做,因为主 AppState 中没有 feature 状态:

export interface AppState {
    router: RouterReducerState<RouterStateUrl>;
}

typescript 指示错误 this.store.select('feature') 因为主商店 AppState 没有 feature 键。

使用选择器:this.store.select(selectFeatureValue) 我收到运行时错误:

export const selectFeatureModule = createFeatureSelector<FeatureState>('feature');
export const selectFeatureValue = createSelector(selectFeatureModule ,
(state: FeatureState) => state.someValue);

我在主 AppComponent 中遇到错误:

TypeError: Cannot read property 'someValue' of undefined

最佳答案

我认为,这是一个至少部分有效的问题。想象一下以下结构:

appState
├── coreState
│
├── lazyModuleSate1
│   ├── subStateA
│   └── subStateB
│
└── lazyModuleSate2
    ├── subStateA
    └── subStateB
  • coreState 可能包含有关用户、 session ...的公共(public)信息

  • 惰性模块的缩减器可能需要在处理操作时访问此类公共(public)状态。

    但是

  • 核心模块的 Reducer 只能看到 coreState。

  • 惰性模块的 Reducer(使用 ActionReducerMap 定义)只能看到它们自己的子状态。 对于大多数情况来说,它很好很干净,但有时,应该在 coreState 的条件下处理操作。 不会有问题的,coreState 一直在 store 中。

  • 惰性模块中定义的 Metareducer 只能看到它们自己的 lazyModuleState。 处理子状态之间的互连仍然很有用,但它们对处理 coreState - lazyModuleSate 关系没有帮助。

  • 只有在应用程序级别定义的全局元还原器才能看到 coreState。 可以在这里进行 handel 操作,尽管非常难看。

关于 Angular ngrx-store : How to share store among modules (main module/feature module),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47029436/

相关文章:

typescript - 获取 Ts/Js 文件中 Svelte 存储变量的当前值

angular - @ngrx/store pre-load guard catch 错误

angular - 如何使用 forFeature 而不用于延迟加载模块?

angular - 在这个例子中为什么模板变量的值是 "ngModel"

javascript - Angular E2E 测试让隐藏元素仅在 E2E 期间显示

javascript - Angular2 动画媒体查询

从 : npm i angular-star-rating 开始的 Angular 星级

typescript - 扩展 VSCode,自定义 UI

typescript 错误 : Getter-only property not defined in literal

angularjs - ngrx 参数选择函数