Search code examples
angulartypescriptrxjsngrxangular12

Multiple Http calls in one @ngrx/effect


I am very confused, and new to @ngrx so please forgive me for not understanding how this is supposed to work.

Let's say I have an effect that is called PlaceOrderEffect

In this effect, I want to process each request in order.

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()
   ]
)

How can I run these in sequential order and handle the final response?


Solution

  • concatMap is RxJS operator to be used with pipe, to merge the source observable with the new one returned by concatMap, which is not your case.

    I think you can use RxJS concat function to achieve what you're trying to do if the requests don't depend on each other, like the following:

    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()
                )
            )
        )
    );
    

    But if each request depends on the previous one, you can use concatMap operator like the following:

    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))
        )
    );