Search code examples
angularreduxngrx

Angular 6 / NGRX Combine Reducers


I am using Angular 6 w/ NgRX 4. I have multiple reducers I would like to combine.

app.module.ts

  import { BrowserModule } from '@angular/platform-browser';
    import { NgModule } from '@angular/core';

    import { StoreModule } from '@ngrx/store';
    import { EffectsModule } from '@ngrx/effects';

    import { StoreDevtoolsModule } from '@ngrx/store-devtools';

    import { AppComponent } from './app.component';
    import counterEffects from './store/counter/counter.effects';

    import reducers from './store/reducers';

    @NgModule({
      declarations: [AppComponent],
      imports: [
        BrowserModule,
        StoreModule.forRoot(reducers),
        EffectsModule.forRoot([counterEffects]),
        StoreDevtoolsModule.instrument({
          maxAge: 10,
        }),
      ],
      providers: [],
      bootstrap: [AppComponent],
    })
    export class AppModule {}

reducers.ts

import { combineReducers } from '@ngrx/store';
import { reducer as counterReducer, key as counterKey } from './counter';
import { reducer as profileReducer, key as profileKey } from './profile';

const appReducer = combineReducers({
  [counterKey]: counterReducer,
  [profileKey]: profileReducer,
});

export default (state, action) => {
  if (action.type === 'REDIRECT_TO_EXTERNAL') {
    state = undefined;
  }

  return appReducer(state, action);
};

My reducers are standard reducers, nothing special there.

Coming from a React / Redux background, I would set multiple reducers up like this, however in Angular when I attempt to select from the store I get undefined. When I attempt to view the store using the dev tools, I can see none of my reducers and state is simply {}

How do I setup multiple reducers in Angular 6 / NgRX 4?


Solution

  • import { ActionReducerMap } from '@ngrx/store';
    import { reducer as counterReducer, key as counterKey } from './counter';
    import { reducer as profileReducer, key as profileKey } from './profile';
    
    export interface IAppState {
      [counterKey]: any;
      [profileKey]: any;
    }
    
    export const reducers: ActionReducerMap<IAppState> = {
      [counterKey]: counterReducer,
      [profileKey]: profileReducer,
    };