ngrx store Effects & Selectors - Tuong-Nguyen/Angular-D3-Cometd GitHub Wiki
- Used to manage side effects
 - Similar to 
redux-thunk,redux-saga, create new action from old action 
npm install @ngrx/effect --save
- Use in calling sync request
 - The store dispatch a LOAD action and return LOAD_SUCCESS or LOAD_FAIL action
 
- Define an effect service
 - Create effect
 - Import effect to module
 
- Decorate with 
@Injectable() - Inject the data service through constructor
 
@Injectable()
export class WidgetEffects {
  constructor(
    private actions$: Actions,
    private widgetService: WidgetService,
  ) {}
}- Decorate with 
@Effect() - Effect return an 
ObservableofAction - 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)))
    );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 });
    // ...
  });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
 
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');Returns a callback function for selecting a slice of state.
export const getWidgets = createSelector(
  getWidgetsState, // createFeatureSelector<WidgetsState>('widgets');
  (state: WidgetsState) => state.widgets.items
);