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

Angular 15嵌套懒加载子路由异常:加载父组件而非子组件问题

问题原因与解决方案

核心问题:父组件缺少 <router-outlet>

你的嵌套子路由不生效的根本原因是:GamesComponent 作为父路由组件,模板里没有添加 <router-outlet> 标签。

Angular的子路由组件必须通过父组件内的 <router-outlet> 才能渲染。当你访问 /dashboard/games/game/123 时,Angular已经匹配到games路由并加载了GamesComponent,但因为没有渲染出口,子路由的GameComponent无处挂载,页面自然只会显示GamesComponent的内容。

而把game/:id移到和games同级时,它变成了dashboard的子路由,会渲染在UserDashboardComponent的<router-outlet>里,所以能正常工作。

修复步骤

  1. 打开GamesComponent的模板文件(如games.component.html)
  2. 添加<router-outlet>标签,位置根据布局需求放置,示例:
<!-- GamesComponent 原有内容 -->
<h2>游戏列表</h2>
<!-- 子路由组件将在此渲染 -->
<router-outlet></router-outlet>
  1. 保持原有路由配置不变即可:
const routes: Routes = [{
    path: 'dashboard',
    loadComponent: () => import('./app/user-dashboard/user-dashboard.component').then((m) => m.UserDashboardComponent),
    canActivate: [AuthGuard],
    children: [
      {
        path: '',
        redirectTo: 'games',
        pathMatch: 'full'
      },
      {
        path: 'games',
        loadComponent: () => import('./app/user-dashboard/games/games.component').then((m) => m.GamesComponent),
        children: [
          {
            path: 'game/:id',
            loadComponent: () => import('./app/user-dashboard/games/game/game.component').then((m) => m.GameComponent)
          }
        ]
      }
    ]
}];

bootstrapApplication(AppComponent,
  {
    providers: [
      importProvidersFrom(RouterModule.forRoot(routes, { enableTracing: true }))
    ]
  })

补充说明

  • 独立组件模式下,路由逻辑和传统模块模式完全一致,子路由依然依赖父组件的<router-outlet>
  • 开启enableTracing: true可在控制台查看路由匹配全过程,能看到Angular确实匹配到了子路由,但因无出口无法渲染组件

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 19:31:18