State management in Angular with NgRx

Runtime checks

Runtime checks

Runtime checks

@NgModule({
  imports: [
    StoreModule.forRoot(reducers, {
      runtimeChecks: {
        strictImmutability: true,
        strictStateSerializability: true,
        strictActionSerializability: true,
      },
    }),
  ],
})
export class AppModule {}

Code practice

Schematics

Scaffolding library for Angular applications using NgRx libraries

npm install @ngrx/schematics -D

Schematics

ng generate @ngrx/schematics:store State
  --root --module app.module.ts
ng generate @ngrx/schematics:effect App
  --root --module app.module.ts
ng generate @ngrx/schematics:action user

Schematics

ng generate @ngrx/schematics:store State
  --root --module app.module.ts
ng generate @ngrx/schematics:effect App
  --root --module app.module.ts
ng generate @ngrx/schematics:action user

Schematics

ng config cli.defaultCollection @ngrx/schematics
ng generate action user

Demo

NgRx Entity

NgRx Entity

  • Reduces boilerplate for managing a collection of entities
  • Built-in CRUD operations
  • Built-in selectors

NgRx Entity

interface EntityState<V> {
  ids: string[] | number[];
  entities: { [id: string | id: number]: V };
}

interface State extends EntityState<User> {
  selectedUserId: number | null;
}


const adapter: EntityAdapter<User>
  = createEntityAdapter<User>();

Code practice

Meta reducers

Meta reducers

export function debug(reducer: ActionReducer<any>){
  return function(state, action) {
    console.log('state', state);
    console.log('action', action);
 
    return reducer(state, action);
  };
}
 
export const metaReducers: MetaReducer<any>[] = [debug];
 
@NgModule({
  imports: [
    StoreModule.forRoot(reducers, { metaReducers })
  ],
})
export class AppModule {}

Code practice

Testing

Testing

  • provideMockStore
  • overrideSelector
  • jasmine-marbles

Integration testing

Use the 'real' Store

Selectors

export const selectTotal = createSelector(
  selectSumEvenNums,
  selectSumOddNums,
  (evenSum, oddSum) => evenSum + oddSum
);

describe('My Selectors', () => {
  it('should calc selectTotal', () => {
    expect(selectTotal.projector(2, 3)).toBe(5);
  });
});

Code practice

NgRx Data

NgRx Data

  • manage collections of entities (domain models) without the code
  • based on metadata config
  • provides all the NgRx parts, HTTP methods, and extension points

Thanks!

NgRx Workshop Advanced

By Adrian Faciu

NgRx Workshop Advanced

More topics that we can look into during the workshop.

  • 857