You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular点击食谱跳转详情页路由异常与属性读取报错如何解决

问题修复方案

你一共存在3处核心错误,按顺序修复即可解决所有问题:

1. 路由跳转路径错误

  • 问题原因:你当前处于/recipes路由下,使用相对路径书写routerLink时会直接拼接当前路径,导致最终跳转路径变为/recipes/recipes/xxx,不符合预期。
  • 修复方案:把routerLink改为绝对路径,或者用Angular推荐的数组写法:
<!-- 绝对路径写法 -->
<a routerLink="/recipes/{{recipe.Id}}" routerLinkActive="true">{{recipe.name}}</a>
<!-- 数组写法(更规范) -->
<a [routerLink]="['/recipes', recipe.Id]" routerLinkActive="true">{{recipe.name}}</a>

2. 详情页赋值逻辑错误

  • 问题原因:你在接口回调里使用了==比较运算符,而非=赋值运算符,导致recipe变量从未被正确赋值,模板读取时为undefined,才会抛出读取name属性失败的错误。
  • 修复方案:修改赋值语句:
// 把 == 改成 =
this.sharedService.getRecipeById(id).subscribe(recipe => this.recipe = recipe);

3. 单条食谱接口请求错误

  • 问题原因:Angular HttpClient的get方法第二个参数是请求配置项,不是路径参数,你当前的写法无法把id传到后端,接口拿不到正确数据。
  • 修复方案:把id直接拼接到请求路径上:
getRecipeById(val:any){
  return this.http.get<any>(`${this.ApiUrl}/Recipes/${val}`);
}

可选优化:添加模板空值保护

可以给模板加空值判断,避免接口请求返回前的短时间内模板报错:

<!-- 写法1:用可选链 -->
<h2>Name : {{recipe?.name}}</h2>
<h2>RecipeBody: {{recipe?.recipeBody}}</h2>
<h2>IntendedUse: {{recipe?.IntendedUse}}</h2>
<h2>CoffeeId: {{recipe?.coffeeId}}</h2>

<!-- 写法2:外层加ngIf判断 -->
<ng-container *ngIf="recipe">
  <h2>Name : {{recipe.name}}</h2>
  <h2>RecipeBody: {{recipe.recipeBody}}</h2>
  <h2>IntendedUse: {{recipe.IntendedUse}}</h2>
  <h2>CoffeeId: {{recipe.coffeeId}}</h2>
</ng-container>

内容的提问来源于stack exchange,提问作者Griefing

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 21:06:03