Select Page

The paramMap processing is a bit tricky. When the map changes, you get() the id parameter from the changed parameters.

Then you tell the HeroService to fetch the hero with that id and return the result of the HeroService request.

You might think to use the RxJS map operator. But the HeroService returns an Observable<Hero>. So you flatten the Observable with the switchMap operator instead.

The switchMap operator also cancels previous in-flight requests. If the user re-navigates to this route with a new id while the HeroService is still retrieving the old idswitchMap discards that old request and returns the hero for the new id.

The observable Subscription will be handled by the AsyncPipe and the component’s hero property will be (re)set with the retrieved hero.