Search code examples
angularngrxngrx-effects

NgRx effects - mapping actions to make sequential service calls and updating store


I want to pass the same action 2 successive times with different entities, for example I want to add 2 entities,

this.store.dispatch(new Add(entity1));
this.store.dispatch(new Add(entity2));

the problem that I encountered is that I got the result of only one action (the entity 2 one) and this is the effect of my action. I want to wait for the result of the first action before passing the second action.

@Effect()
add$ = this.actions$
  .ofType<Add>(ADD)
  .pipe(switchMap(a =>
    this.sharedService.add(a.entity, a.api)
      .pipe(map(s => new AddResult(Ok(s.id))))
  .pipe(catchError(e => of(new AddResult(Err(e)))))));

Solution

  • You may want to use mergeMap instead of switchMap. Here is list of Map with their behaviour: enter image description here

    @effect()
    add$ = this.actions$
    .ofType<Add>(ADD)
    .pipe(mergeMap(a =>
    this.sharedService.add(a.entity, a.api)
    .pipe(map(s => new AddResult(Ok(s.id))))
    .pipe(catchError(e => of(new AddResult(Err(e)))))));