3

我是一名后端开发人员,从我正在从事的项目的前端开发开始。前端使用 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)
      );
    }),
   );

我想实现这样的目标

   @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)
      );
    }),
   );

我认为这是我对 RxJs 的了解不足,这使我无法实施该条件。

4

2 回答 2

6

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

I recommend you read: 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)
      );
    }),
   );

于 2019-11-24T22:30:35.363 回答
2

To dispatch multiple actions you can pass the action array as shown below:

@Effect()
getTodos$ = this.actions$.ofType(todoActions.LOAD_TODOS).pipe(
  switchMap(() => {
    return this.todoService
      .getTodos()
      .pipe(
        switchMap(todos => [
          new todoActions.LoadTodosSuccess(todos),
          new todoActions.ShowAnimation()
        ]),
        catchError(error => of(new todoActions.LoadTodosFail(error)))
      );
  })
);

To dispatch actions conditionally you can wrap the actions in if/else as shown below:

@Effect()
getTodos$ = this.actions$.ofType(todoActions.LOAD_TODOS).pipe(
  switchMap(() => {
    return this.todoService
      .getTodos()
      .pipe(
        switchMap(todos => {
         if(true) {
             return new todoActions.LoadTodosSuccess(todos),
         } else {
            return new todoActions.ShowAnimation()
         }),
        catchError(error => of(new todoActions.LoadTodosFail(error)))
      );
  })
);

Hope that helps!

于 2019-12-06T14:31:01.167 回答