BACK
Use casesDependent HTTP chain — a request depends on the response
Use cases · 24

Dependent HTTP chain — a request depends on the response

Pattern

To load permissions you need user.id from the first request. To load the dashboard you need permission.scope from the second. There's no parallel option — it's a sequential chain.

The problem it solves

Imperatively this turns into a pyramid of subscribes: subscribe inside subscribe inside subscribe. Cancellation on route change falls apart — the old chain keeps running. Error handling is smeared across every level.

Operators and why they matter

  • switchMap — passes the previous request's result into the next, and cancels the whole chain on a new top-level trigger (a new id in the URL, say).
  • map — assembles the final response into the needed VM.
  • catchError — handles a failure at ANY stage of the chain in one place.

Gotchas

  • mergeMap — on a trigger change (new id in the URL), the old chain keeps running in parallel with the new one. Chaos with responses.
  • forkJoin won't work here — the second request doesn't know its parameter ahead of time; you must wait for the first.
  • catchError in the middle of the chain — you'll catch the error and send the next request with default values. A train with no rails.

What you get

A dependent load becomes one Observable with a clear success/error contract. Cancellation works atomically across the whole chain.

script.ts // TypeScript
CONSOLE · Console output
Hit Run to see the result...