如何有条件地从 ngrx 中的效果分派多个动作

Aka*_*rma 2 rxjs ngrx ngrx-effects rxjs-pipeable-operators rxjs-observables

我是一名后端开发人员,从我正在从事的项目的前端开发开始。前端使用Angular7和NgRx。在过去的 4 天里,我学习了很多东西,但这里有一些我被困住的地方,希望得到您的帮助。

我了解到我们可以通过返回一个具有多个动作的 Observable 数组来从 NgRx 中的效果中分派多个动作。我想根据条件调度数组中的一个动作。

我的代码看起来像这样

@Effect()
  something$: Observable<Action> = this.actions$.pipe(
    ofType(ActionType),
    switchMap.(action: any) => {
       return service.call(action.payload)
         .pipe(
             switchMap((data: ReturnType) => [ 
                new Action1(),
                new Action2(),
              ]),
        catchError(error handling)
      );
    }),
   );
Run Code Online (Sandbox Code Playgroud)

我想实现这样的目标

   @Effect()
  something$: Observable<Action> = this.actions$.pipe(
    ofType(ActionType),
    switchMap.(action: any) => {
       return service.call(action.payload)
         .pipe(
             switchMap((data: ReturnType) => [ 
                 if(condition)
                   new Action1()
                  else
                    new Action1.1() ,
                new Action2(),
              ]),
        catchError(error handling)
      );
    }),
   );
Run Code Online (Sandbox Code Playgroud)

我认为是我对 RxJs 缺乏了解,这阻碍了我实现该条件。

Ale*_*edt 5

您可以通过让条件 if 确定要返回的可迭代对象来分派多个操作或特定操作

我建议你阅读:https : //www.learnrxjs.io/operators/transformation/switchmap.html

  @Effect()
  something$: Observable<Action> = this.actions$.pipe(
    ofType(ActionType),
    switchMap(action: any) => {
       return service.call(action.payload)
         .pipe(
             switchMap((data: ReturnType) => {
                 let actionsToDispatch = [];
                 if(condition) {
                   actionsToDispatch.push(new SomeAction())
                 } else {
                   actionsToDispatch.push(new SomeOtherAction())
                 }
                 return actionsToDispatch
              }),
              catchError(error handling)
      );
    }),
   );

Run Code Online (Sandbox Code Playgroud)