How to Trigger the same API With different parameters everytime in NGRX and aggregate the response?

Viewed 210

So I have this case where in , I have to trigger a single API , but each time with different paramaters .

Consider -> https://stackoverflow.com/posts/postId=1234

I have a list of postId , say [ 1234 , 6653 , 7192 ] . I need to parallely hit the Above API with the different postId as mentioned in the above Array . I need to combine the response finally, of each API's response .

How can we achieve this in Ngrx Effects ? Any suggestion is much appreciated . Thanks in advance .

1 Answers

See https://timdeschryver.dev/snippets#multiple-service-calls-from-an-effect for more info.

You're probably looking for the forkJoin operator from RxJS.

refresh$ = createEffect(() =>
  this.actions$.pipe(
    ofType(CustomerActions.refresh),
    exhaustMap(({ customerIds }) =>
      forkJoin(
        ...ids.map((id) =>
          this.customersService.getCustomer(id).pipe(
            map(CustomerActions.getCustomerSuccess),
            catchError((err) =>
              of(CustomerActions.getCustomerFailed(id, err.message)),
            ),
          ),
        ),
      ),
    ),
    map(responseArray => /* Aggregate here */),
  ),
)
Related