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

Angular 5子路由无法正常工作问题求助

排查Angular 5路由问题:/post/:slug 跳转到 NotFoundComponent

我来帮你分析一下问题所在,主要有两个核心点需要调整:

1. 子路由依赖父组件的 <router-outlet>

你的PostRoutingModule把:slug路由设置成了PostHomeComponent的子路由,但如果PostHomeComponent的模板里没有添加<router-outlet>标签,Angular就找不到渲染子组件PostDetailComponent的位置,这会直接导致路由匹配失败,最终触发通配符路由跳转到NotFoundComponent。

解决方案一:给PostHomeComponent添加router-outlet

打开PostHomeComponent的模板文件,添加<router-outlet>标签,子组件会在这个标签位置渲染:

<!-- post-home.component.html -->
<h1>Post Home Page</h1>
<router-outlet></router-outlet>

2. 调整路由结构(更推荐的简化方式)

如果你不需要PostHomeComponent作为PostDetailComponent的父容器,完全可以把两个路由设置为同级,这样就不需要依赖父组件的router-outlet,逻辑更清晰:

修改PostRoutingModule的路由配置:

const routes: Routes = [
  { path: '', component: PostHomeComponent }, // 匹配 /post
  { path: ':slug', component: PostDetailComponent } // 匹配 /post/:slug
];

额外的小修复:PostDetailComponent中的类型转换错误

你的PostDetailComponent里把字符串类型的slug强制转成了数字:

const id = +this.route.snapshot.paramMap.get('slug');

但test-post-title是字符串,用+转换会得到NaN,应该直接获取字符串类型的slug:

ngOnInit() {
  const slug = this.route.snapshot.paramMap.get('slug');
  console.log(slug); // 输出 "test-post-title"
}

按照上面的步骤调整后,访问/post/test-post-title应该就能正常加载PostDetailComponent了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 07:33:24