loading...

Multiple service calls from an NgRx Effect

timdeschryver profile image Tim Deschryver Originally published at timdeschryver.dev ・1 min read

Follow me on Twitter at @tim_deschryver | Originally published on timdeschryver.dev.


Multiple service calls from an Effect

Use case

An action to fetch multiple entities at once, but the service has only an endpoint to fetch one entity at a time.

Solution

Use the RxJS merge operator to flatten all request streams and concurrently emit all values to a single output stream.

refresh$ = createEffect(() =>
  this.actions$.pipe(
    ofType(CustomerActions.refresh),
    exhaustMap(({ customerIds }) =>
      merge(
        ...ids.map(id =>
          this.customersService.getCustomer(id).pipe(
            map(CustomerActions.getCustomerSuccess),
            catchError(err =>
              of(CustomerActions.getCustomerFailed(id, err.message)),
            ),
          ),
        ),
      ),
    ),
  ),
)

Follow me on Twitter at @tim_deschryver | Originally published on timdeschryver.dev.

Posted on by:

timdeschryver profile

Tim Deschryver

@timdeschryver

NgRx team member - Writer for AngularInDepth

Discussion

markdown guide