Angular 4懒加载模块子路由无法跳转问题求助
解决Angular 4懒加载路由子组件跳转报错问题
首先,你的问题核心出在懒加载模块的路由配置逻辑错误,导致子路由路径匹配失败。我们一步步拆解修正:
1. 修正Home模块的路由结构
你的home.routes里错误地给子路由套了一层额外的path: 'home'父路径,但实际上根路由app.routes已经把/home路径指向了HomeModule,所以HomeModule内的路由应该是相对于/home路径的,不需要重复定义home父节点。
错误的原路由配置:
export const router: Routes = [ { path: '', component: HomeComponent, pathMatch: 'full' }, { path: 'home', component: HomeComponent, children: [ { path: 'addItem/:groupName', component: AddItemComponent }, { path: 'addGroup', component: AddGroupComponent }, ] } ];
修正后的正确路由:
export const router: Routes = [ // 匹配 /home 路径,挂载HomeComponent并加载子路由 { path: '', component: HomeComponent, children: [ { path: 'addItem/:groupName', component: AddItemComponent }, { path: 'addGroup', component: AddGroupComponent }, ] } ];
2. 确认routerLink的写法
你在HomeComponent模板里写的[routerLink]="['addGroup']"是完全正确的——这是相对当前路由(/home)的路径,会自动生成/home/addGroup,刚好匹配我们修正后的路由规则。
如果偏好绝对路径写法,也可以写成[routerLink]="['/home/addGroup']",两种方式都能正常工作。
3. 额外验证点
- 确认HomeModule里
RouterModule.forChild(router)的导入是正确的(你的现有代码没问题); - 确认HomeComponent模板里的
<router-outlet></router-outlet>存在(用来渲染子组件,你的代码也已经包含)。
为什么之前会报错?
之前的路由配置中,子路由的实际匹配路径是/home/home/addGroup,但你点击routerLink时跳转的是/home/addGroup,两者不匹配,所以Angular抛出了Cannot match any routes. URL Segment: 'home/addGroup'的错误。修正路由结构后,路径匹配逻辑就正常了。
内容的提问来源于stack exchange,提问作者Sreehari
相关产品推荐
相关产品推荐

