您可以使用快照或可观测对象从路由中获取ID.我更喜欢可观察的,因为URL有时可以编程方式更改,如果模板/视图也更新就好了.
路由文件必须如下所示(不带大括号):
{
path: "Detail/:Id",
component: DetailInfoComponent
}
因为您希望等待数据绑定准备就绪,所以可以在ngOnInit生命周期钩子中访问它.
// 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'];
});
}
还添加了一个console.log,以确保您正在获取值,并且没有其他任何操作.
要使用快照获取它,您可以做(确保将0替换为您期望id的索引:
const foodID = this.route.snapshot.url[0]!.path;
请记住,并不是每个平台上的文件名和文件夹都区分大小写.就我个人而言,我只在应用程序中使用小写,但这可能是我个人的偏好.
此外,不使用[href],而是使用[routerLink]来正确使用ANGING的路由.例如.
<a class="card_img" [routerLink]="['/Detail/', food.id]">
这将按预期推送和弹出导航堆栈.但是,请确保在您的导入中包括RouterModule.[routerLink]期望字符串或路径元素array.