NgRx:在单个效果中调度多个操作

Ras*_*ani 19 rxjs ngrx ngrx-effects angular

我需要在调用 API 请求后分派多个操作。我目前正在使用此代码在 API 请求完成后分派一个操作:

 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)
))));
Run Code Online (Sandbox Code Playgroud)

在这个效果中调度更多的动作很重要,不能为此编写另一个效果。

Dei*_*sch 30

您可以使用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)
))));
Run Code Online (Sandbox Code Playgroud)

编辑:
虽然可以做到,但你不应该这样做。
看看 no-multiple-actions-in-effects


tim*_*ver 12

这里的所有答案都是正确的,“简单”的答案和解决方案是返回一组操作。然而,这是一个不好的做法,有关更多信息,请参阅NgRx ESLint 文档中的“No Multiple Actions In Effects” 。