How to return a map of reducers in getReducers(): ActionReducerMap<fromFeature.State>?

vulp picture vulp · Oct 21, 2017 · Viewed 8.9k times · Source

I'm trying to inject feature reducers when composing state through NgRx feature modules.

import { NgModule, InjectionToken } from '@angular/core';
import { StoreModule, ActionReducerMap } from '@ngrx/store';

import * as fromFeature from './reducers';

export const FEATURE_REDUCER_TOKEN = new InjectionToken<ActionReducerMap<fromFeature.State>>('Feature Reducers');

What I am supposed to return here?

export function getReducers(): ActionReducerMap<fromFeature.State> {
  // map of reducers
  return {
  
  };
}

I tried

export function getReducers(): ActionReducerMap<fromFeature.State> {
      // map of reducers
      return {
          reducerA: FeatureAReducer
      };
    }

But it gives the error Object literal may only specify known properties.

The rest of module code:

@NgModule({
  imports: [
    StoreModule.forFeature('feature', FEATURE_REDUCER_TOKEN),
  ],
  providers: [
    {
      provide: FEATURE_REDUCER_TOKEN,
      useFactory: getReducers
    }
  ]
})
export class FeatureModule { }

Answer

vulp picture vulp · Oct 21, 2017

I thought that each reducer, whether it is root or feature reducer, returns a new state object. But actually it doesn't. What feature reducer does, it returns only the segment of the state which it updates.

From the ngrx/platform/example-app:

we treat each reducer like a table in a database. This means our top level state interface is just a map of keys to inner state types.