Web Developer

Section 24 NgRx/store

NgRx devtools: search: redux devtools extensions; then choose: zalmoxisus/redux-devtools-extension: Redux … – GitHub, then go to website: http://extension.remotedev.io/, choose browser you use.

  • Set up NgRx devtools in Angular:
    • npm install –save–dev @ngrx/store-devtools
    • In app.module.ts file, import StoreDevtoolsModule from @ngrx/store-devtools
    • in NgModule imports, StoreDevtoolsModule.instrument({ logOnly: environment.production}) (note: this environment is just environment, but not environment.prod.ts)
  • Also can install NgRx Router: npm install –save @ngrx/router-store
    • then set up in app.module.ts: import StoreRouterConnectingModule from @ngrx/router-storeM
    • also in NgModule to import: StoreRouterConnectingModule.forRoot()

Set up NgRx in Angular: npm install –save @ngrx/store

Reducer is a function: export function shoppingListReducer(state, action: Action) {}

Action is class, including properties: type, payload(target dealing with reducer)

Set up reducer map in app.module.ts file, import StoreModule from @ngrx/store, and also import in NgModule: StoreModule.forRoot({shoppingList: shoppingListReducer (note: reducer function)});

  • Set up store in xxx.component.ts file:
    • import { Store } from ‘@ngrx/store’;
    • constructer (private store: Store<{shoppingList: {xxx: xxxx(note: type of the reducer return)}>;)

Note: ! very important: in Reducer file, in order to make generic type accepted, the interface can be set up for different reducers, and also set up one interface for all reducers combination, which could be signed for any store imported by ts files located in different component

  • Set up Root state:
    • export interface AppState { shoppingList: fromShoppingList.State; auth: fromAuth.State;} (Note: this interface tells Angular: what kind of state should be accepted by properties: shoppingList and auth)
    • export const appReducer: ActionReducerMap<AppState> = { shoppingList: fromShoppingList.shoppingListReducer, auth: fromAuth.authReducer}; (Note: the generic type tells Angular in the object, it should include shoppingList and auth properties, and also tells Angular, what kinds of reducer should be used to deal with the state (shoppingList and auth))

Two important notice:

  1. any dispatch or actions will reach all reducers, so make sure the identifier is unique, normally use feature module’s name as prefixed, such as “[shopping list] Login
  2. because any action will go through all reducers, all reducers’ switch loop should include default: state statement to make sure the correct state returns from the reducers
Previous Article