使用@ ngrx / store到angular 2模块

时间:2016-12-01 10:11:29

标签: angular state ngrx

我已成功在当前应用程序中使用@ ngrx / store(也是@ ngrx / effects和@ ngrx / store-devtools)。现在我想制作模块,这将是独立于应用程序其余部分的理想选择。问题是如何在其中使用@ngrx / store? 我可以以某种方式将新的reducer添加到现有的" app"商店?我想避免将模型从模块转移到应用程序并将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 {
}

还有人知道如何在devtool上显示@ ngrx / store的名字吗?将它从ngrx-store-some_random_number更改为某个app_name?

非常感谢

1 个答案:

答案 0 :(得分:2)

从ngrx4开始,您将商店提供为: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 {}

然后feature状态将存储在state.feature键下。

使用可以使用选择器一致地访问功能商店:

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

在要素模块中:Angular组件可以使用/切片状态:

...
constructor(private store: Store<AppState>,) {
    this.store.select(selectFeatureValue)
        .subscribe(console.log.bind(console));

}
...