Sub topic 10
Reacting to Route Parameters with ActivatedRoute
This chapter assumes you know how to declare Angular routes and use routerLink. It also assumes you can read a pipe chain with map and filter, have seen switchMap cancel an earlier request, and know how the async pipe and takeUntilDestroyed manage a subscription. Earlier chapters covered all of these. Here you apply them to the router. The router exposes the current URL's parameters as observables, and reading them correctly is where many detail pages go wrong.
Why the Router Hands You Observables
When a user goes to /products/7, the router creates the matching component. It also gives that component an ActivatedRoute, an injectable object that describes the route segment the component belongs to. ActivatedRoute has two ways to read parameters:
snapshot: a plain object holding the parameter values as they were when the component was created.paramMap,queryParamMap,data,url, andfragment: observables that emit a new value each time that part of the route changes.
These two forms exist because the router reuses components. Say the user is on /products/7 and clicks a link to /products/8. Both URLs match the same route config, so by default the router keeps the existing ProductDetailComponent instance and only updates its route. The constructor does not run again, and ngOnInit does not fire again. Any value you read once from snapshot now describes the wrong product.
The Snapshot Trap
This component looks correct and passes a quick manual test:
import { Component, inject } from '@angular/core';
import { ActivatedRoute, RouterLink } from '@angular/router';
@Component({
selector: 'app-product-snapshot',
standalone: true,
imports: [RouterLink],
template: `
<p>Product {{ productId }}</p>
<a routerLink="/products/8">Related product</a>
`,
})
export class ProductSnapshotComponent {
productId = inject(ActivatedRoute).snapshot.paramMap.get('id') ?? '';
}Load /products/7 and the page shows "Product 7". Click "Related product" and the URL changes to /products/8, but the page still says "Product 7". This bug only appears when the user navigates from one parameter value to another on the same route. Users trigger it through "next" and "previous" links, related-item lists, and the browser back button.
Reading paramMap Reactively
paramMap emits a ParamMap object. Its get(name) method returns string | null, getAll(name) returns string[], and has(name) returns a boolean. The observable behaves like a BehaviorSubject: when you subscribe, it emits the current parameters synchronously, and it emits again on each later change.
The simplest reactive version uses the pattern from the earlier chapter on unsubscribing:
import { Component, inject } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { map } from 'rxjs';
@Component({
selector: 'app-product',
standalone: true,
template: `<p>Product {{ productId }}</p>`,
})
export class ProductComponent {
productId = '';
constructor() {
inject(ActivatedRoute)
.paramMap.pipe(
map(params => params.get('id') ?? ''),
takeUntilDestroyed()
)
.subscribe(id => (this.productId = id));
}
}takeUntilDestroyed() must be called in an injection context, so it goes in the constructor or a field initializer. Angular's documentation says router-provided ActivatedRoute observables are cleaned up when the routed component is destroyed. Even so, keep takeUntilDestroyed or the async pipe. Once you add operators such as switchMap, the subscription also holds inner work, and cleaning it up explicitly costs nothing and protects you if the code is later moved somewhere the router doesn't manage.
Loading Data per Parameter with switchMap
A real detail page fetches data for each id. In this case, every new parameter makes the previous request irrelevant, so switchMap is the right operator. If the user clicks through three products quickly, only the last response gets rendered.
import { Component, inject } from '@angular/core';
import { AsyncPipe } from '@angular/common';
import { ActivatedRoute, RouterLink } from '@angular/router';
import { HttpClient } from '@angular/common/http';
import { distinctUntilChanged, filter, map, switchMap } from 'rxjs';
interface Product {
id: string;
name: string;
relatedId: string;
}
@Component({
selector: 'app-product-detail',
standalone: true,
imports: [AsyncPipe, RouterLink],
template: `
@if (product$ | async; as product) {
<h2>{{ product.name }}</h2>
<a [routerLink]="['/products', product.relatedId]">Related product</a>
} @else {
<p>Loading…</p>
}
`,
})
export class ProductDetailComponent {
private route = inject(ActivatedRoute);
private http = inject(HttpClient);
product$ = this.route.paramMap.pipe(
map(params => params.get('id')),
filter((id): id is string => id !== null),
distinctUntilChanged(),
switchMap(id => this.http.get<Product>(`/api/products/${id}`))
);
}The matching route definition:
import { Routes } from '@angular/router';
import { ProductDetailComponent } from './product-detail.component';
export const routes: Routes = [
{ path: 'products/:id', component: ProductDetailComponent },
];Each operator has a job:
| Operator | Why it is there | Column |
|---|---|---|
| `map(params => params.get('id'))` | Pulls one value out of the `ParamMap` so later operators work on a plain string. | |
| `filter(... !== null)` | Narrows the type from `string \ | null` to `string` and skips emissions where the parameter is missing. |
| `distinctUntilChanged()` | `paramMap` can emit when other parts of the route change. This stops a refetch when the id itself stayed the same. | |
| `switchMap(...)` | Cancels the in-flight request for the previous id and subscribes to the new one. |
The async pipe owns the subscription, so no manual cleanup is needed. Add catchError inside the switchMap projection, as the error-handling chapter showed, so that one failed id doesn't end the whole stream and leave the page dead for every later navigation.
Query Parameters and Route Data
queryParamMap works the same way for the part of the URL after ?. A product list that reads ?page=3 might look like this:
import { Component, inject } from '@angular/core';
import { AsyncPipe } from '@angular/common';
import { ActivatedRoute, RouterLink } from '@angular/router';
import { map } from 'rxjs';
@Component({
selector: 'app-product-list',
standalone: true,
imports: [AsyncPipe, RouterLink],
template: `
@if (page$ | async; as page) {
<p>Page {{ page }}</p>
<a routerLink="." [queryParams]="{ page: page + 1 }">Next page</a>
}
`,
})
export class ProductListComponent {
private route = inject(ActivatedRoute);
page$ = this.route.queryParamMap.pipe(
map(params => {
const page = Number(params.get('page') ?? '1');
return Number.isInteger(page) && page > 0 ? page : 1;
})
);
}Route parameters always arrive as strings, so you have to convert and validate them yourself. The URL is user input, and ?page=banana is a request you must handle.
route.data emits the static data object from the route config merged with any resolver results. It is an observable for the same reason: a resolver runs again when parameters change on a reused component.
Gotchas
Parent and child parameters
An ActivatedRoute sees only the parameters of its own route segment. Take a child route reviews nested under products/:id. The child component's paramMap does not contain id by default. You can read it through route.parent?.paramMap, or you can configure provideRouter(routes, withRouterConfig({ paramsInheritanceStrategy: 'always' })) so that children inherit their parents' parameters. Query parameters are global to the URL and visible from every route.
Null handling
get returns null when a parameter is absent. A mandatory :id segment is always present on that route, but optional parameters and query parameters often are not. Narrow the type explicitly. Don't use ! to tell the compiler the value exists.
Component input binding as an alternative
If you add withComponentInputBinding() to provideRouter, the router writes route parameters, query parameters, and data into component inputs that have matching names. An id = input<string>() then updates on every navigation, including reuse. This approach suits components that only display values. When you need cancellation or debouncing, or when you combine the parameter with other streams, the observable pipeline is often clearer. The signals chapter shows how to convert an input back into an observable.
Choosing an approach
| Approach | Updates on component reuse | Best for |
|---|---|---|
| `snapshot.paramMap` | No | Values that cannot change while the component lives |
| `paramMap` + `takeUntilDestroyed` | Yes | Imperative side effects, such as writing to a field |
| `paramMap` + `switchMap` + async pipe | Yes | Loading data per parameter with cancellation |
| `withComponentInputBinding` | Yes | Simple display of parameter values as inputs |
Exercise
A user on /orders/12 clicks a link to /orders/15. The OrderComponent reads the id with inject(ActivatedRoute).snapshot.paramMap.get('id') in a field initializer and fetches the order in ngOnInit. What does the page show after the click, and why?
Show answer
It still shows order 12. Both URLs match the same route config, so the router reuses the existing component instance. The field initializer and ngOnInit don't run again, so the snapshot value and the fetched order stay stale. Fix it by deriving the order from route.paramMap with switchMap.
Exercise
In the ProductDetailComponent pipeline, what goes wrong if you replace switchMap with mergeMap, and what goes wrong if you drop the catchError recommended inside the projection?
Show answer
With mergeMap, quick navigation keeps every request alive, and a slow response for an older id can arrive last and overwrite the current product. Without catchError inside the projection, one failed HTTP request sends an error notification through the outer stream. That terminates the subscription, so later parameter changes never load anything until the component is recreated.
Exercise
A child route 'reviews' is nested under 'products/:id'. Inside ReviewsComponent, route.paramMap.get('id') returns null. Give two ways to read the product id.
Show answer
Read it from the parent segment with route.parent?.paramMap.pipe(map(p => p.get('id'))), or set paramsInheritanceStrategy to 'always' through withRouterConfig in provideRouter so that the child's paramMap includes its parents' parameters.