我有以下组件结构
所以我的路由看起来像这样:
const childroutes = [
{
path: '',
children: [
{ path: 'edit', component: EditProjectComponent},
{ path: 'subres1', component: Subres1Component},
{ path: 'subres2', component: Subres2Component},
{ path: 'subres3', component: Subres3Component},
{ path: 'subres4', component: Subres4Component}
]
}
]
{
path: 'project/:projectId',
component: ProjectDetailComponent,
children: childroutes,
resolve: { project: ProjectResolver} /** resolve Project from ProjectService **/
}
正如您所看到我从服务中解析我的Projectdata并可以通过
在ProjectDetailComponent中访问它们this.route.snapshot.data
现在的问题是,我如何将“EditProjectComponent”中解析的数据传递给它的所有子路由组件?
我现在可以执行以下操作来解决子组件中的项目数据:
const childroutes = [
{
path: '',
children: [
{ path: 'edit', component: EditProjectComponent,resolve: { project: ProjectResolver}},
{ path: 'subres1', component: Subres1Component,resolve: { project: ProjectResolver}},
{ path: 'subres2', component: Subres2Component,resolve: { project: ProjectResolver}},
{ path: 'subres3', component: Subres3Component,resolve: { project: ProjectResolver}},
{ path: 'subres4', component: Subres4Component,resolve: { project: ProjectResolver}}
]
}
]
但这看起来很丑陋和错误。
答案 0 :(得分:12)
这里有两个选项:
1. 您可以通过创建特定于孩子的解析程序并访问路线的父级属性,通过子级解析程序访问父级解析数据。
[... module.ts | ... component.ts] 强>
{
path: 'project/:projectId',
component: ProjectDetailComponent,
resolve: { project: ProjectResolver }
children: [
{
path: ':projectId/edit',
component: EditProjectComponent,
resolve: { edit: EditProjectResolve }
}
]
}
修改项目-component.ts 强>
ngOnInit() {
this.edit = this.route.snapshot.data.edit;
}
2。您可以一起绕过子进程的解析器,并从子组件中访问父数据。
[... module.ts | ... component.ts] 强>
{
path: 'project/:projectId',
component: ProjectDetailComponent,
resolve: { project: ProjectResolver }
children: [
{
path: ':projectId/edit',
component: EditProjectComponent
}
]
}
修改项目-component.ts 强>
ngOnInit() {
this.route.parent.data
.subscribe((data) => {
this.edit = data.edit;
});
}
答案 1 :(得分:3)
您只需要在子组件中执行此操作:
ngOnInit() {
this.route.parent.data
.subscribe((data) => {
this.edit = data.edit;
});
}