Setting up StoreModule in ngrx 4.0

Aravind
Aravind
Jul 23, 2017 · 1 min read
  1. Create a interface for AppStore, a collection of all the states.
app.store.tsexport interface AppStore {
loaderSlice: LoaderSlice;
}

2. Create actions separately which will be of class and type(instead of enums)

actions.tsimport { Action } from “@ngrx/store”;
export const ShowLoader = ‘Showing Loader’
export const HideLoader = ‘Hiding Loader’
export class SHOW_LOADER implements Action {
readonly type = ShowLoader
}
export class HIDE_LOADER implements Action {
readonly type = HideLoader
}
export type Actions = SHOW_LOADER | HIDE_LOADER;

Note: Each action will have a type so you should be implementing Action interface from ngrx/store

3. Create a reducer and a state interface for strict typing(LoaderSlice in our example)

reducer.tsexport interface LoaderSlice {
showOverlayLoader: boolean;
}
let initialState: LoaderSlice = {
showOverlayLoader: false
};
export function reducer
(state = initialState,
action: LOADER_ACTIONS.Actions): LoaderSlice {
switch (action.type) {
case LOADER_ACTIONS.ShowLoader: {
initialState.showOverlayLoader = true;
return Object.assign({},initialState);
}
case LOADER_ACTIONS.HideLoader:
return Object.assign({},initialState);
default:
return initialState;
}
}

4. This is the additional step you need to do in order to register your reducer.

reducer.factory.tsimport * as loaderReducer from “app/store/reducers/loader.reducer”;
import { AppStore } from “app/store/app.store”;
export const reducers: ActionReducerMap<AppStore> = {
loaderSlice: loaderReducer.reducer
};

Note: Registering reducers to a generic object of type ActionReducer<T>

5.Import statement in your module by supplying the reducer factory

StoreModule.forRoot(reducers)

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade