angularrxjsngrxngrx-effects

NgRx: dispatch multiple actions in a single effect


I need to dispatch multiple actions after calling an API request in my effect. I'm using this code at the moment to dispatch one action after API request done:

 changeStatus$ = createEffect(() => 
  this.actions$.pipe(
    ofType(fromJtDetail.changeStatus),
    switchMap(action =>
      this.jtDetailService.changeStatus(action.entity,action.jobTicketId).pipe(
        map(res => fromJtDetail.statusChanged({changedStatus: action.entity.newStatus})),
        catchError(error => EMPTY)
))));

It's important to dispatch more actions in this effect, can't write another effect for this.


Solution

  • You can dispatch multiple actions using switchMap + of(

    changeStatus$ = createEffect(() => 
      this.actions$.pipe(
        ofType(fromJtDetail.changeStatus),
        switchMap(action =>
          this.jtDetailService.changeStatus(action.entity,action.jobTicketId).pipe(
          switchMap(res => of(
            fromJtDetail.statusChanged({changedStatus: action.entity.newStatus}),
            fromHere.doSmthAction(),      // <-- additional action 1
            fromThere.doSmthElseAction(), // <-- additional action 2
          )),
          catchError(error => EMPTY)
    ))));
    

    EDIT:
    Althought it can be done you should not do it.
    Have a look at no-multiple-actions-in-effects

    EDIT2: The initial link is from a now archived repo. The rule is still correct, it simply got moved to the NgRx core. Check here no-multiple-actions-in-effects