Angular 36: Route Parameters & Guards
easy⏱ 5 mincourseangular
Parameterized paths: :id captures a URL segment
{ path: 'user/:id', component: UserComponent } matches any URL like /user/42 or /user/abc, and the router extracts whatever appeared in that segment as a route parameter named id.
export const routes: Routes = [
{ path: 'user/:id', component: UserComponent },
];
Reading params: snapshot vs. the reactive paramMap
inject(ActivatedRoute).snapshot.paramMap.get('id') reads the id once, at the moment the component is created — fine if the component is always destroyed and recreated on navigation. If the router might reuse the same component instance while only the :id changes (navigating from /user/1 to /user/2 without leaving the route), subscribe to the reactive inject(ActivatedRoute).paramMap observable instead so you catch every update.
private route = inject(ActivatedRoute);
userId = this.route.snapshot.paramMap.get('id');
// or, reactively:
// this.route.paramMap.subscribe(params => {
// this.userId = params.get('id');
// });
CanActivateFn: a plain function that gatekeeps navigation
A route guard is just a function matching the CanActivateFn signature — it can inject() any service it needs (an auth service, the Router itself), and returns true to let navigation proceed, false to block it silently, or a UrlTree (from inject(Router).createUrlTree([...])) to redirect elsewhere. It's attached to a route with canActivate: [authGuard].
export const authGuard: CanActivateFn = () => {
const auth = inject(AuthService);
const router = inject(Router);
if (auth.isLoggedIn()) return true;
return router.createUrlTree(['/login']);
};