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

Angular已保存菜谱页跳转报Cannot match any routes错误如何解决

问题原因

你当前使用的是相对路径配置routerLink,当页面处于/saved-recipes路由下时,Angular会将你配置的['recipe', recipe.id]直接拼接在当前活跃路由之后,最终生成的访问路径是/saved-recipes/recipe/637876,和你在路由表中配置的根层级recipe/:id规则无法匹配,因此抛出错误。

解决方案

最简便的修复方式是将相对路径改为绝对路径,只需要给routerLink数组的第一个路径项添加前缀斜杠即可,这样路由会直接从应用根路径开始匹配,不受当前页面路由影响。
修改后的按钮代码如下:

<button class="btn btn-primary me-3" [routerLink]="['/recipe', recipe.id]" style="text-decoration: none;">Show Full
  Recipe</button>

如果你的业务确实需要将菜谱详情作为「已保存菜谱」页面的子路由展示,可调整路由配置并添加子路由出口,方案如下:

  1. 修改路由配置,新增子路由规则:
const routes: Routes = [
  { path: '', component: HomeComponent },
  { path: 'recipe/:id', component: RecipeDetailsComponent },
  { 
    path: 'saved-recipes', 
    component: SavedRecipesComponent,
    children: [
      { path: 'recipe/:id', component: RecipeDetailsComponent }
    ]
  }
];
  1. 在SavedRecipesComponent的模板文件中添加<router-outlet></router-outlet>,用于渲染子路由对应的菜谱详情组件。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 17:06:05