【问题标题】:Ngrx effect dispatch different actions - best practiceNgrx 效果调度不同的动作 - 最佳实践
【发布时间】:2022-11-16 01:57:07
【问题描述】:

我正在尝试根据分成几种效果的类型来分派不同的动作。我知道我做错了什么或以错误的方式思考,所以我分享我的担忧。

用例如下:

  • 我有几个动作必须链接到相同的效果,因为两个动作,接受和选择都必须通知后端:
notifyChangeInBack$ = createEffect(
    () => {
      return this.actions$.pipe(
        ofType(
          InteractionActions.interactionAccepted,
          InteractionActions.interactionSelected,
        ),
        exhaustMap(action => {
          const { interaction } = action;
          return this.interactionDatasource.notifyInteractionChange(interaction)
            .pipe(
              map(() => InteractionActions.changeInteractionSuccess({ interaction })),
              catchError(() => of(InteractionActions.changeInteractionError({ interaction })))
            )
        })
      );
    }
  );
  • 随后,在分派changeInteractionSuccess 操作后,根据操作类型执行不同的功能。如果操作是interactionAccepted,则用户必须导航到具体页面。如果操作是interactionSelected,则用户必须导航到基于逻辑的 url。现在,我这样做有两个效果:
navigateToCustomer$ = createEffect(
    () => {
      return this.actions$.pipe(
        ofType(InteractionActions.interactionAccepted),
        tap((action) =>
          // logic for navigation...
        )
      );
    },
    { dispatch: false }
  );

navigateToLastInteractionState$ = createEffect(
    () => {
      return this.actions$.pipe(
        ofType(InteractionActions.interactionSelected),
        concatLatestFrom(() => this.interactionFacade.selectInteractionsUi$),
        tap(([action, interactionsUi]) => {
          // logic for navigation...
        })
      );
    },
    { dispatch: false }
  );

我的问题是:我怎样才能连接changeInteractionSuccess 动作后通知与需要上一个动作的不同效果返回?我应该创建两个不同的效果来通知支持分别收听动作吗?即:interactionAccepted 操作的一个效果,它执行请求并返回正确的操作,interactionSelected 操作也是如此。

提前谢谢了!!!

【问题讨论】:

    标签: angular ngrx ngrx-effects


    【解决方案1】:

    您可以嵌套动作,这是一种侦听动作 X 的模式,然后等待 Y 发生。例如:

    navigateToCustomer$ = createEffect(
        () => {
          return this.actions$.pipe(
            ofType(InteractionActions.interactionAccepted),
            switchMap((action) => {
               return this.actions$.pipe(ofType(InteractionActions.changeInteractionSuccess))
            })
          );
        },
        { dispatch: false }
      );
    

    【讨论】:

      猜你喜欢
      • 2018-11-22
      • 1970-01-01
      • 2022-01-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-06-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多