[英]How to properly setup nested routing in angular
我正在尝试使用嵌套路径设置角度路线。 父页面是/list
子页面是/list/:id
出于某种原因,以下路线不起作用。 如果我导航到/list/:id
,会找到路由,但它会加载ListComponent
而不是ViewComponent
{
path: 'list',
component: ListComponent,
children: [
{
path: ':id',
component: ViewComponent
}
]
}
我很确定这与angular doc 中的示例设置相同。 我错过了什么吗?
以下有效,但它的层次结构错误, /list
是/list/:id
兄弟
{
path: 'list',
children: [
{
path: '',
component: ListComponent
},
{
path: ':id',
component: ViewComponent
}
]
}
在第一个示例中,由于 ViewComponent 是 ListComponent 的子项,因此您必须根据您的 stackblitz 示例在 list.component.html 中添加<router-outlet></router-outlet>
:
<p>
list works!
</p>
<a [routerLink]="['./view']">view</a>
or
<button (click)="buttonClick()">view</button>
<!-- add the line below here-->
<router-outlet></router-outlet>
ViewComponent 被加载到你放置路由器插座的地方。
当您转到路由 /list/:id 时,这将使 Angular 加载 ListComponent 和 ViewComponent,因为 ViewComponent 是 ListComponent 的子项。
每条有孩子的路线,都需要有<router-outlet></router-outlet>
标签。
例如,如果 ListComponent 是导航侧栏,并且 ViewComponent 包含来自后端的数据,则此架构很有用(以及许多其他类型的情况)。
编辑
如果您不想在访问 /list/:id 路由时同时加载 ListComponent 和 ViewComponent,则可以将路由更改为如下所示:
const mainRoutes: Routes = [
{
path: 'list',
component: ListComponent,
},
{
path: 'list/:id',
component: ViewComponent
}
];
当您使用此架构时,仅在您访问“list/:id”时加载 ViewComponent,因为 ViewComponent 不是 ListComponent 的子项。
在这个例子中,你不应该在 list.component.html 中使用 router-outlet
由于 ViewComponent 是一个子组件,您必须在父组件中渲染它。 您可以通过在 ListComponent 中添加<router-outlet></router-outlet>
来实现。 它会解决你的问题。
以前,在一个项目中,我是通过以下方式完成的(我更改了组件的名称以匹配您的组件):
const routes: Routes = [
{
path : 'list',
component: ListComponent
},
{
path : 'list/:id',
component: ViewComponent
},
{
path : '**',
component: ListComponent
}
];
然后在进口中:
@ngModule({
imports: [RouterModule.forChild(routes)]
})
希望有帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.