
Same Route, New :id, Same Component: Why ngOnInit Doesn't Run Again
- كاتب موثّق
- Angular 22
محتويات المقال
/users/1 to /users/2, but the page still shows the first user's name, photo and posts. Press F5 and it's suddenly correct. QA files it as intermittent, because it never happens when you arrive from the user list or type the URL by hand. The component reads the id once, in ngOnInit, from route.snapshot, and ngOnInit doesn't run a second time.
The common misconception
ngOnInit runs again with the new id. "Init" sounds like "page load", and a component looks like a page.
this.route.snapshot.paramMap.get('id') in ngOnInit for precisely that flow. Typing a URL or pressing F5 reloads the whole app, which creates everything again. The only path that exposes the difference, a link from one detail page to another of the same kind, is also the one nobody tests first.
What actually happens
The router compares route configs, not URLs
BaseRouteReuseStrategy, reuses a route when the matched router config is identical. /users/1 and /users/2 both match the same { path: 'users/:id' } entry, so the existing component stays. The API docs spell out the purpose: the component isn't destroyed and recreated when only the route parameters, query parameters or fragment change.
ngOnInit, and no ngOnDestroy for the old one either. What does change is the route state the component can observe: the ActivatedRoute stays the same object, and its params, paramMap, queryParams and data Observables emit the new values.
A snapshot is a photo
route.snapshot.paramMap.get('id') gives you the id at that moment, as a plain string, and nothing tells your code when the URL moves on. Read it once in ngOnInit, and the component keeps loading, displaying and saving user 1 while the address bar says 2.
Local state survives, too
Resolvers rerun; snapshot reads don't
runGuardsAndResolvers policy, paramsChange, the router reruns them when path or matrix parameters change, though not for query parameters. So a resolver fetches user 2 correctly, and a component that reads route.snapshot.data once in ngOnInit still never sees the result.
The fix: read the id as a signal
provideRouter(routes, withComponentInputBinding()), and the router sets component inputs from path, matrix and query parameters, static route data and resolver data, by matching their names. When a key disappears from the route, the input is set to undefined, so old values don't linger.
import { HttpClient } from '@angular/common/http';import { Component, inject, OnInit, signal } from '@angular/core';import { ActivatedRoute } from '@angular/router';@Component({ selector: 'app-user-page', template: `<h1>{{ user()?.name }}</h1>`,})export class UserPage implements OnInit { private readonly route = inject(ActivatedRoute); private readonly http = inject(HttpClient); readonly user = signal<User | undefined>(undefined); ngOnInit() { // Runs once per instance: /users/1 → /users/2 keeps user 1 const id = this.route.snapshot.paramMap.get('id'); this.http .get<User>(`/api/users/${id}`) .subscribe((u) => this.user.set(u)); }}import { httpResource } from '@angular/common/http';import { Component, input } from '@angular/core';@Component({ selector: 'app-user-page', template: ` @if (user.hasValue()) { <h1>{{ user.value().name }}</h1> } `,})export class UserPage { // Bound from :id, and updated when only the param changes readonly id = input.required<string>(); // A new request each time id changes; a pending one is cancelled readonly user = httpResource<User>(() => `/api/users/${this.id()}`);}httpResource() reads this.id(), so it sends a new request whenever the id changes and cancels the one still in flight, which also means a fast double click can't leave user 1's response on user 2's page. Anything else derived from the id, a computed() title or a linkedSignal() tab, updates the same way.
ActivatedRoute: turn route.paramMap.pipe(map((p) => p.get('id'))) into a signal with toSignal(), or pipe it into an operator that handles the request. Which flattening operator you choose there matters, and switchMap is right for this kind of read.
ngOnInit | |
route.snapshot | |
paramMap, params and data Observables | |
withComponentInputBinding() | |
How to apply it in your project
Find one-time route reads Search components for snapshot.paramMap,snapshot.params,snapshot.queryParamsandsnapshot.data. Each one in a route that can link to itself is a stale-data bug waiting for the right click.Turn route values into inputs Add withComponentInputBinding()toprovideRouter(), declareinput()s named after the parameters, and derive requests and titles from them withhttpResource()andcomputed().Reset state that belongs to one entity List what the page keeps locally, such as tabs, drafts, selections and pagination, and reset each item when the id changes, with a linkedSignal()sourced from the id or an explicit reset.Test detail-to-detail navigation Add an end-to-end test that goes from one detail page to another through a link and asserts that the heading and the requests changed.
Key takeaways
The default BaseRouteReuseStrategykeeps the component when the route config matches and only params change.The constructor and ngOnInitrun once per instance, so an id read fromroute.snapshotthere goes stale.Local state survives reuse too; reset what belongs to one entity when the id changes. Read route values as signals, with withComponentInputBinding()ortoSignal(route.paramMap), and derive the rest.
التعليقات (0)