我有一个关于Angular 5中的路由的问题。我想创建一个子路由但是当我键入url(用于子路由)时,父组件被加载。我的路由:
path: 'user-admin/:id',
component: UserAdminComponent,
},
children: [
{
path: '',
component: UserAdminComponent,
pathMatch: 'full'
},
{
path: "final-exams",
component: FinalExamsComponent,
},
属于问题的两条路线:
http://localhost:4200/user-admin/0
http://localhost:4200/user-admin/0/final-exams
提前谢谢你的帮助! :)
看看工作解决方案
user-admin/1 //您好将被打印
user-admin/1/final-exams // Hola将成为输出
问题是:
您在父路由中未提及Parent和Child Route&Children路由中提到相同的组件
const appRoutes: Routes = [
{
path: 'user-admin/:id',
// component: HelloComponent, // No need to mention the same component, in parent
children: [ // Children routes are inside the parent route
{
path: '',
component: HelloComponent,
pathMatch: 'full'
},
{
path: "final-exams",
component: HolaComponent
}
]
}
];
在让孩子们进入之前你正在关闭这条道路:
{
path: 'user-admin/:id',
component: UserAdminComponent,
children: [
{path: '', component: UserAdminComponent, pathMatch: 'full'},
{path: 'final-exams', component: FinalExamsComponent},
]
},
目前,你在开始使用}
之前放置了一个children
。
如果在final-exams
中找到的路线FinalExamsComponent
及其内容需要与UserAdminComponent
的内容一起呈现,则可以使用无组件路径来实现您的需求。像这样
{
path: 'user-admin/:id',
component: UserAdminComponent,
children: [
{ path: ''},
{ path: "final-exams", component: FinalExamsComponent },
]
}
这样,当你去http://localhost:4200/user-admin/0时,你将只渲染与UserAdminComponent
相关的user-admin/:id
。访问http://localhost:4200/user-admin/0/final-exams然后将呈现UserAdminComponent
和FinalExamsComponent
的内容
您可以阅读有关无组件路线here的信息。
在这种情况下,您不需要将子路由添加到UserAdminComponent并打开/关闭大括号,如下所示。试试这个代码。
{ path: user-admin/:id', component: UserAdminComponent,
children: [
{ path: 'final-exams', component: FinalExamsComponent},
//add child routes here
]
},