ActivatedRoute to get route parameters. Which option correctly describes how to access a parameter named id synchronously?constructor(private route: ActivatedRoute) {}
ngOnInit() {
// How to get 'id' parameter synchronously?
}The ActivatedRoute provides a snapshot property for synchronous access to route parameters. The paramMap is a map-like object with a get() method to retrieve parameters safely as strings or null.
Option A correctly uses this.route.snapshot.paramMap.get('id').
id changes from '5' to '10'?constructor(private route: ActivatedRoute) {}
ngOnInit() {
this.route.params.subscribe(params => {
console.log(params['id']);
});
}The params observable emits a new value whenever the route parameters change. So the console will log '5' first, then '10' after the parameter changes.
userId parameter from ActivatedRoute?constructor(private route: ActivatedRoute) {}
ngOnInit() {
const userId = ???
}Option C tries to access userId as a property of paramMap, which is incorrect. paramMap requires the get() method to retrieve parameters.
userId property does not update when the route parameter changes. What is the likely cause?userId: string | null = null; constructor(private route: ActivatedRoute) {} ngOnInit() { this.route.params.subscribe(params => { params['userId']; }); }
The subscription callback reads params['userId'] but does not assign it to this.userId. So the component property remains unchanged.
paramMap instead of params to access route parameters?paramMap is a map-like object with methods like get() that return null if a parameter is missing, avoiding undefined errors. It provides a cleaner and safer API than the plain object params.