ngrx store Effects & Selectors - Tuong-Nguyen/Angular-D3-Cometd GitHub Wiki

Effect

  • Used to manage side effects
  • Similar to redux-thunk, redux-saga, create new action from old action

Install

npm install @ngrx/effect --save

Example

  • Use in calling sync request
  • The store dispatch a LOAD action and return LOAD_SUCCESS or LOAD_FAIL action

Usage

  • Define an effect service
  • Create effect
  • Import effect to module

Define Effect Service

  • Decorate with @Injectable()
  • Inject the data service through constructor
@Injectable()
export class WidgetEffects {
  constructor(
    private actions$: Actions,
    private widgetService: WidgetService,
  ) {}
}

Create Effect

  • Decorate with @Effect()
  • Effect return an Observable of Action
  • switchMap operator: Maps each value to an Observable, then flattens all of these inner Observables using switch.
import * as widgetManagement from '../actions/widgets';
// ...

  @Effect()
  loadWidgets$: Observable<Action> = this.actions$
    .ofType(widgetManagement.LOAD)
    .switchMap(() =>
      this.widgetService.getAll()
        .map((widgets: Widget[]) => new widgetManagement.LoadSuccess(widgets))
        .catch(error => of(new widgetManagement.LoadFail(error)))
    );

Test Effect

provideMockAction method from @ngrx/store/testing

 // ...
 let actions: Observable<any>;

  beforeEach(() => {
    TestBed.configureTestingModule({
      providers: [
        MyEffects,
        provideMockActions(() => actions),
        // other providers
      ],
    });
    // ...
  });

  it('should work', () => {
    actions = hot('--a-', { a: SomeAction });
    // ...
  });

Selectors

Selector is used for watching a piece of data in store. It is an Observable and only emit items when the new item is different from the previous one (shallow compare)

  • Getter function to fetch a slice of store

createFeatureSelector

It returns a typed selector function for a feature slice of state.

export interface WidgetsState {
  widgets: fromWidgets.State;
}

export interface State extends fromRoot.State {
  widgets: WidgetsState;
}

export const getWidgetsState = createFeatureSelector<WidgetsState>('widgets');

createSelector

Returns a callback function for selecting a slice of state.

export const getWidgets = createSelector(
  getWidgetsState, // createFeatureSelector<WidgetsState>('widgets');
  (state: WidgetsState) => state.widgets.items
);
⚠️ **GitHub.com Fallback** ⚠️