DEV Community

Tim Deschryver
Tim Deschryver

Posted on • Originally published at timdeschryver.dev

6 3

Multiple service calls from an NgRx Effect

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)),
            ),
          ),
        ),
      ),
    ),
  ),
)
Enter fullscreen mode Exit fullscreen mode

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

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (1)

Collapse
 
goldsam profile image
Sam G

Doesn't this violate the "one action per effect" best practice?

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay