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

Angular路由无法匹配子路由:嵌套路由出口导航异常求助

Angular嵌套路由导航错误解决方案

错误原因

你在导航时错误地重复了父路由路径companies,导致路由尝试匹配不存在的companies/companies/:id路径,触发NG04002路由匹配失败错误。

你的路由配置中,companies是父路由,对应CmsLayoutComponent,它的子路由''和:id直接挂载在cms outlet下,不需要在导航时再次指定companies。

正确导航写法

1. 导航到公司详情页(推荐相对路由写法)

利用相对路由,基于当前激活的路由进行导航:

import { ActivatedRoute } from '@angular/router';

// 注入ActivatedRoute
constructor(private router: Router, private route: ActivatedRoute) {}

viewCompany(companyId: number) {
  // ../ 表示回到父路由层级,再拼接id
  this.router.navigate(['../', companyId], { relativeTo: this.route });
}

2. 直接指定outlet的子路由片段

如果要显式指定outlet,只需传入子路由的部分(不需要companies):

viewCompany(companyId: number) {
  this.router.navigate([{ outlets: { cms: [companyId] } }], { relativeTo: this.route });
}

3. 导航回公司列表页

// 方法1:相对路由回到列表
this.router.navigate(['../'], { relativeTo: this.route });

// 方法2:指定outlet为空路径
this.router.navigate([{ outlets: { cms: [''] } }], { relativeTo: this.route });

额外说明

确保CmsLayoutComponent模板中存在名称为cms的路由出口:

<router-outlet name="cms"></router-outlet>

内容的提问来源于stack exchange,提问作者A. Vreeswijk

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 17:02:27