在 Angular 2 模块中使用 @ngrx/store

3

我目前在应用程序中成功地使用了 @ngrx/store(还有 @ngrx/effects 和 @ngrx/store-devtools)。现在我想制作一个模块,这个模块最好独立于应用程序的其他部分。问题是如何在其中也使用 @ngrx/store?我是否可以将新的 reducer 添加到现有的“app”store 中? 我希望避免将模型从模块移动到应用程序并将 reducer 注册到应用程序中。有没有人有解决方案?以下是示例代码:

// App declarations
export const APP_IMPORTS = [
  .
  .
  .
  StoreModule.provideStore(reducer),
  EffectsModule.run(someEffects),
  STORE_DEV_TOOLS_IMPORTS
];

@NgModule({
  declarations: [
    APP_DECLARATIONS,
    AppComponent
  ],
  imports: [
    APP_IMPORTS
  ],
  providers: [APP_PROVIDERS],
  bootstrap: [AppComponent]
})
export class AppModule {
}

在新模块中:

// Module declaration
@NgModule({
  imports: [CommonModule, 
           FormsModule, 
           StoreModule.provideStore({ counter: counterReducer }) // <-- how to change this to just add to current store new reducer??
  ],
  exports: [MyTestComponent],
  declarations: [MyTestComponent],
})
export class SomeModule {
}

还有谁知道如何更改@ngrx/store在devtool中显示的名称?将其从ngrx-store-some_random_number更改为某个app_name?

非常感谢


目前有几个与此相关的未解决问题:https://github.com/ngrx/store/issues/281 和 https://github.com/ngrx/store/issues/211。同时,还有一个提议中但尚未实施的更改:https://gist.github.com/MikeRyan52/5d361681ed0c81e38775dd2db15ae202。 - cartant
这将是一个非常好的东西。我们能改变当前商店的名称吗? - CoYoTe
1个回答

2
从ngrx4开始,您可以通过以下方式提供store:StoreModule.forRoot({router: routerReducer})
@NgModule({
    imports: [
        StoreModule.forRoot({router: routerReducer}),
        EffectsModule.forRoot([...]),
        ...
    ],
    declarations: [],
    ...
})
export class AppModule {}

然后在您的特性模块中,您可以提供存储作为StoreModule.forFeature(...)

@NgModule({
    imports: [
        StoreModule.forFeature('feature', featureReducer),
        EffectsModule.forFeature([...]),
        ...
    ],
    declarations: [],
    ...
})
export class FeatureModule {}
< p > feature 状态将会被存储在 state.feature 键中。

使用选择器可以一致地访问 feature 存储:

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

在特性模块中,Angular组件可以使用/slice作为状态的方式:
...
constructor(private store: Store<AppState>,) {
    this.store.select(selectFeatureValue)
        .subscribe(console.log.bind(console));

}
...

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接