BACK
Use casesRoute param load — loading by id from the URL
Use cases · 18

Route param load — loading by id from the URL

Pattern

The URL is the source of truth. /users/1 must show user 1, /users/2 — user 2. When the id in the URL changes, we load the new user.

The problem it solves

The user clicks fast: /users/1 → /users/2. The request for id=1 is still in flight when the request for id=2 goes out. If the slow response for id=1 arrives after id=2, the wrong user ends up on the page. An imperative subscribe-inside-subscribe from ActivatedRoute won't handle it.

Operators and why they matter

  • distinctUntilChanged — the Router sometimes re-emits the same id. Guard against a needless reload.
  • switchMap — a new id cancels the old load. The response race is solved.
  • map — turns the server DTO into a page view model.
  • catchError inside switchMap — an error becomes a page state instead of killing the route stream.

Gotchas

  • mergeMap — an old slow response can repaint the page of the new id. The classic bug.
  • concatMap — forces a wait for the load of an already-irrelevant page. The user sees a "stuck" interface.
  • catchError outside the whole pipeline — one error stops all future route transitions. Put it only inside switchMap.

What you get

The page always matches the latest id in the URL. An error is a normal page state, not broken navigation.

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