Issue
I have this type of <a>
<a class="card_img" [href]="'/Detail/' + food.id">
Route looks like:
{
path: "Detail/:{Id}",
component: DetailInfoComponent
}
So, problem: I can`t get Id, i used this method
this.route.params.subscribe(params => {
this.foodID = params['Id'];
});
And foodID is undefined. Wrere is my fault and how i can get ID correctly?
Solution
You can get the id from the route using a snapshot or an observable. I prefer observables, because the URL can sometimes change programmatically and it's nice if the template/view updates as well.
Your routing file must look like this (without the curly braces):
{
path: "Detail/:Id",
component: DetailInfoComponent
}
Since you want to wait for data bindings to be ready, you can access it in the ngOnInit lifecycle hook.
// On top of your Class - For unsubscribing from observables automatically - Injection context
private destroyRef = inject(DestroyRef);
ngOnInit() {
this.route.params.pipe(
takeUntilDestroyed(this.destroyRef)
).subscribe(params => {
console.log(params);
this.foodID = params['Id'];
});
}
Also added a console.log to make sure you're getting the value, and nothing else is going on with async operations.
To get it using a snapshot, you can do (make sure you replace the 0 with whatever the index you expect the id to be:
const foodID = this.route.snapshot.url[0]!.path;
Keep in mind that file names and folders aren't case-sensitive on every platform. Personally i only use lowercase in Apps, but that might be a personal preference.
Also, instead of using [href], use [routerLink] to use Angular's router properly. For example.
<a class="card_img" [routerLink]="['/Detail/', food.id]">
This wil push and pop the navigation stack as expected. Make sure to include the RouterModule though in your imports. [routerLink] exxpects either a string, or an array of path elements.
Answered By - Novel Approaches
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.