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?
2
Answers
Route path must be without "{}"
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):
Since you want to wait for data bindings to be ready, you can access it in the ngOnInit lifecycle hook.
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:
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.
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.