角度传递将数据解析为子路线 [英] Angular pass resolve data to child-routes
问题描述
我具有以下组件结构
- 项目
- 编辑项目
- sub-ressource1
- sub-ressource2
- sub-ressource3
- project
- edit-project
- sub-ressource1
- sub-ressource2
- sub-ressource3
所以我的路由如下:
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中访问它们:
As you can see i resolve my Projectdata from a service and can access them in ProjectDetailComponent via
this.route.snapshot.data
所以现在的问题是,如何将在"EditProjectComponent"中解析的数据传递给它的所有子路由组件?
So now the question is, how can i pass the data resolved in "EditProjectComponent" to all its childroutes components?
我现在可以执行以下操作来解析子组件中的项目数据:
I now that i could do the following to resolve project-data in childcomponents:
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}} ] } ]
但这似乎很丑陋和错误.
But this seems ugly and wrong.
推荐答案
您在这里有两个选择:
1..您可以通过创建子级特定的解析器并访问路由的父级属性,通过子级的解析器访问父级解析数据.
1. You can access parent resolve data via the child's resolver by creating a child-specific resolver and accessing the route's parent property.
[... module.ts | ... component.ts]
{ path: 'project/:projectId', component: ProjectDetailComponent, resolve: { project: ProjectResolver } children: [ { path: ':projectId/edit', component: EditProjectComponent, resolve: { edit: EditProjectResolve } } ] }
edit-project-component.ts
ngOnInit() { this.edit = this.route.snapshot.data.edit; }
2..您可以一起绕过子级的解析器,并从子级组件内部访问父级数据.
2. You can bypass the child's resolver all together and access parent data from within the child component.
[... module.ts | ... component.ts]
{ path: 'project/:projectId', component: ProjectDetailComponent, resolve: { project: ProjectResolver } children: [ { path: ':projectId/edit', component: EditProjectComponent } ] }
edit-project-component.ts
ngOnInit() { this.route.parent.data .subscribe((data) => { this.edit = data.edit; }); }
这篇关于角度传递将数据解析为子路线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!