首页 > 解决方案 > 一个 @ngrx/effect 中的多个 Http 调用

问题描述

我很困惑,并且是@ngrx 的新手,所以请原谅我不理解这应该如何工作。

假设我有一个叫做的效果PlaceOrderEffect

在这种情况下,我想按顺序处理每个请求。

processOrder$ = createEffect(
   ofType(OrderActions.PROCESS_ORDER),
   //here is where i get confused
   concatMap([
      this.service.addCrust(),
      this.service.addTopings(),
      this.service.sendToCook()
      this.service.checkOut()
   ]
)

如何按顺序运行这些并处理最终响应?

标签: angulartypescriptrxjsngrxangular12

解决方案


concatMapisRxJS运算符与 一起使用pipe,将源 observable 与返回的新 observable 合并concatMap,这不是你的情况。

如果请求不相互依赖,我认为你可以使用RxJS concat函数来实现你想要做的事情,如下所示:

processOrder$ = createEffect(() =>
    this.actions$.pipe(
        ofType(OrderActions.PROCESS_ORDER),
        // here you need to switch and map to the new observable (concat one) returned by switchMapTo operator
        switchMap(({ payload }) =>
            concat(
                this.service.addCrust(),
                this.service.addTopings(),
                this.service.sendToCook(),
                this.service.checkOut()
            )
        )
    )
);

但如果每个请求都依赖于前一个请求,则可以使用concatMap如下运算符:

processOrder$ = createEffect(() =>
    this.actions$.pipe(
        ofType(OrderActions.PROCESS_ORDER),
        concatMap(({ payload }) => this.service.addCrust(payload)),
        concatMap((response1) => this.service.addTopings(response1)),
        concatMap((response2) => this.service.sendToCook(response2)),
        concatMap((response3) => this.service.checkOut(response3))
    )
);

推荐阅读