Angular延迟加载模块引起的路由问题

问题描述

延迟加载子模块后, 子模块的路由匹配到外层的<router-outlet>

问题出现的环境背景及自己尝试过哪些方法

不使用延迟加载, 能正常拼配到子组件里面的<router-outlet>

相关代码

// 延迟加载子路由 app-routing.module.ts
{ path: 'main', loadChildren: () => import('./pages/main/main.module').then(m => m.MainModule) }

// 子路由 main-routing.module.ts
const routes: Routes = [
    {path: '', component: MainComponent},
    {path: 'pagea', component: PageAComponent},
    {path: 'pageb', component: PageBComponent}
];

// 一般子路由 app-routing.module.ts
{ path: 'main', component: MainComponent, 
    children: [
      { path: 'pagea', component: PageAComponent },
      { path: 'pageb', component: PageBComponent }
]}

// 子组件html模版 main-component.html
<div>
  <p>main works!</p>
  <a routerLink="./pagea" style="margin: 5px">page-a</a>
  <a routerLink="./pageb" style="margin: 5px">page-b</a>
  <div class="outlet">
    <router-outlet>
      <p>Router Outlet Here</p>
    </router-outlet>
  </div>
</div>

你期待的结果是什么?实际看到的错误信息又是什么?

// 使用一般子路由
// 页面A, B能渲染到红色的<router-outlet>上
图片描述

// 使用延迟加载
// 页面A, B渲染到黄色的<router-outlet>上
图片描述

阅读 2.3k
1 个回答

普通子路由你知道用children,为什么异步加载的路由不写到children里面?

// 子路由 main-routing.module.ts
const routes: Routes = [
    {
        path: '', 
        component: MainComponent
        children: [
            {path: 'pagea', component: PageAComponent},
            {path: 'pageb', component: PageBComponent},
        ],
    },    
];
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进