Angular 16从子模块路由至另一懒加载子模块报错排查
解决Angular懒加载模块间路由重定向的报错问题
你遇到的报错是因为相对路径的重定向逻辑不符合预期:当前clientreport路由的redirectTo用的是相对路径,Angular会基于当前激活的路由(clients/client/:id)拼接路径,最终生成clients/client/reporting/reports/reportviewer,这个路径不存在,所以匹配失败。
修复方案
把redirectTo的值改为绝对路径(以斜杠/开头),让Angular从根路由开始匹配目标路径:
修改ClientRoutingModule中的重定向路由:
const routes: Routes = [ { path: '', children: [ { path: 'clients', //site.com/clients component: ClientGridComponent, data: { role: ['ADMIN', 'STAFF'], breadcrumb: 'Client Grid', }, }, { path: 'client', //site.com/clients/client:id component: ClientComponent, data: { role: ['ADMIN', 'STAFF'], breadcrumb: 'Client Details', }, children: [ { path: 'clientreport',//site.com/clients/client:id/clientreport redirectTo: '/reporting/reports/reportviewer', // 改为绝对路径 pathMatch: 'full' // 加上pathMatch确保完全匹配当前路由 }, ], }, { path: '', redirectTo: 'clients', pathMatch: 'full', }, ], }, ]; @NgModule({ imports: [RouterModule.forChild(routes), CommonModule], exports: [RouterModule], }) export class ClientRoutingModule {}
额外验证
确保根路由(AppRoutingModule)中已经正确注册了两个懒加载模块的入口:
const routes: Routes = [ { path: 'clients', loadChildren: () => import('./client/client.module').then(m => m.ClientModule) }, { path: 'reporting', loadChildren: () => import('./reporting/reporting.module').then(m => m.ReportingModule) }, { path: '', redirectTo: '/clients', pathMatch: 'full' } ]; @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule] }) export class AppRoutingModule { }
这样修改后,访问site.com/clients/client:id/clientreport时,会正确重定向到site.com/reporting/reports/reportviewer,匹配到目标懒加载模块的路由。
内容的提问来源于stack exchange,提问作者CodeMan03
相关产品推荐
相关产品推荐

