Angular路由如何跳过menuitem路径的父组件直接加载子组件
Angular路由绕过父级组件的解决方案
你当前的问题根源是:嵌套子路由的组件需要渲染在父路由对应组件的<router-outlet>标签内,你现在MenuItemComponent没有加该标签,所以子组件无法渲染,只会显示父组件的默认内容。如果不需要父组件的任何内容,可以用以下几种方案实现需求:
方案1:使用无组件父路由(最适配你的场景)
直接删除menuitem路由层级的component配置,只保留路径作为公共前缀即可,Angular原生支持这种仅做路径分组、无对应组件的父路由配置,子路由的组件会直接渲染到应用顶层的<router-outlet>中,完全不会加载MenuItemComponent。
修改后的路由配置如下:
const routes: Routes = [ {path: '', redirectTo: '/home', pathMatch: 'full'}, {path: 'home', component: LandingComponent}, // 去掉menuitem层级的component属性,仅作为路径前缀 {path: 'menuitem', children: [ {path: 'create', component: MenuItemCreateComponent}, {path: ':id', component: MenuItemDetailComponent} ]}, {path: 'cart', component: CartComponent} ];
方案2:保留父路由组件,仅渲染子内容
如果后续你可能需要用到menuitem根路径的对应内容,可以保留当前的路由结构,做两处修改即可:
- 将
MenuItemComponent的内容替换为仅保留<router-outlet>标签,删除原有默认的p标签内容:
<router-outlet></router-outlet>
- 如果不需要用户访问
/menuitem根路径,可以给父路由加空路径重定向,避免访问根路径时显示空白:
{path: 'menuitem', component: MenuItemComponent, children: [ {path: '', redirectTo: '/home', pathMatch: 'full'}, {path: 'create', component: MenuItemCreateComponent}, {path: ':id', component: MenuItemDetailComponent} ]},
方案3:平铺路由配置
也可以直接去掉嵌套结构,把两个子路由直接定义为顶级路由,效果完全一致:
const routes: Routes = [ {path: '', redirectTo: '/home', pathMatch: 'full'}, {path: 'home', component: LandingComponent}, {path: 'menuitem/create', component: MenuItemCreateComponent}, {path: 'menuitem/:id', component: MenuItemDetailComponent}, {path: 'cart', component: CartComponent} ];
这种写法适合路由规则少的小型项目,缺点是后续要统一给menuitem前缀的路由加权限守卫、公共配置时不如嵌套写法方便。
内容的提问来源于stack exchange,提问作者rminaj
相关产品推荐
相关产品推荐

