ngRx : differences between keys from state interface and keys from StoreModule.forRoot

Viewed 467

I have just started ngRx and I am facing a small issue.

I would like to know the difference between the keys of both interface states and modules forRoot.

export interface ConfigurationState {
  readonly configuration: Configuration;
}
StoreModule.forRoot({
  configuration: ConfigurationReducer,
}),
export function configurationReducer(state: Configuration = undefined, action: ConfigurationActions.Actions): Configuration {
  switch (action.type) {
    case ConfigurationActions.SET:
      return action.payload;
    default:
      return state;
  }
}
this.store.select('configuration')

When I select a store with the 4th piece of code, I see an intellisense help for the keys of the 1st piece of code.

If I change the key of the 2nd piece of code, it doesn't change anything.

So my question is, what is the purpose of forRoot ? Are the keys important ?

1 Answers

The inerface's job is typechecking and a bit of intellisense. The forRoot is to register your reducers, this is the most important part otherwise your reducers won't get invoked.

In the example you post the State interface isn't really adding any value, but if you do it as follows, it adds some typechecking value.

// reducer.ts

/**
 * As mentioned, 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.
 */
export interface State {
  layout: fromLayout.State;
  router: fromRouter.RouterReducerState;
}

/**
 * Our state is composed of a map of action reducer functions.
 * These reducer functions are called with each dispatched action
 * and the current or initial state and return a new immutable state.
 */
export const reducers: ActionReducerMap<State> = {
  layout: fromLayout.reducer,
  router: fromRouter.routerReducer,
};


// app.module.ts
StoreModule.forRoot(reducers),

Taken from the NgRx example app

Related