@ngrx/store combine multiple reducers from feature module

后端 未结 2 1842
逝去的感伤
逝去的感伤 2021-02-01 08:52

I am currently working on a simple test app to learn more about the @ngrx/store. I have a module called TrainingModule which should store some exercises and more information. T

2条回答
  •  [愿得一人]
    2021-02-01 09:13

    Your setup is almost correct.

    In the createFeatureSelector function you declare a feature key in the root of the store, 'exercises' in the example. So, you are going to select store.exercises.exercises.id for example and feature selector is just a shortcut to store.exercises.

    However, in the StoreModule.forFeature('training', trainingReducers) call you defined 'training' as the root key for your feature module.

    The correct setup could look like this:

    export const featureReducersMap = {
      exercise: exerciseReducer,
      anyOtherKey: anyOtherReducer
    };
    
    StoreModule.forFeature('myFeatureModule', featureReducersMap);
    
    export interface FeatureState{
      exercise: string;
      anyOtherKey: number;
    }
    

    Then write selectors like:

    export const featureSelector = createFeatureSelector('myFeatureModule');
    
    export const exerciseSelector = createSelector(
      featureSelector,
      (state: FeatureState) => state.exercise
    );
    

    It is recommended to store the feature key in the variable instead of hardcoding it.

提交回复
热议问题