Angular pass将数据解析为子路由

enn*_*oid 12 angular angular5

我有以下组件结构

  • 项目
    • 编辑项目
    • 子ressource1
    • 子ressource2
    • 子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 **/
}
Run Code Online (Sandbox Code Playgroud)

正如您所看到的,我从服务中解析了Projectdata,并可以通过ProjectDetailComponent访问它们

this.route.snapshot.data
Run Code Online (Sandbox Code Playgroud)

所以现在的问题是,如何将"EditProjectComponent"中解析的数据传递给它的所有childroutes组件?

我现在可以执行以下操作来解决子组件中的项目数据:

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}}
    ]
  }
]
Run Code Online (Sandbox Code Playgroud)

但这似乎是丑陋和错误的.

Des*_*ond 22

你有两个选择:

1.您可以通过创建特定于子项的解析程序并访问路径的父属性,通过子解析程序访问父解析数据.

[... module.ts | ... component.ts]

{
    path: 'project/:projectId', 
    component: ProjectDetailComponent,
    resolve: { project: ProjectResolver }
    children: [
        { 
            path: ':projectId/edit',
            component: EditProjectComponent,
            resolve: { edit: EditProjectResolve }
        }
    ]
}
Run Code Online (Sandbox Code Playgroud)

编辑项目component.ts

ngOnInit() {
    this.edit = this.route.snapshot.data.edit;
}
Run Code Online (Sandbox Code Playgroud)

2.您可以一起绕过子进程的解析器,并从子组件中访问父数据.

[... module.ts | ... component.ts]

{
    path: 'project/:projectId', 
    component: ProjectDetailComponent,
    resolve: { project: ProjectResolver }
    children: [
        { 
            path: ':projectId/edit',
            component: EditProjectComponent
        }
    ]
}
Run Code Online (Sandbox Code Playgroud)

编辑项目component.ts

ngOnInit() {
    this.route.parent.data
        .subscribe((data) => {
            this.edit = data.edit;
        });
}
Run Code Online (Sandbox Code Playgroud)

  • 值得注意的是,parent 也存在于route.snapshot 中,以防您想要以同步方式获取初始值而不订阅可观察流 (4认同)

小智 5

您只需要在子组件中执行此操作:

ngOnInit() {
    this.route.parent.data
        .subscribe((data) => {
            this.edit = data.edit;
        });
}
Run Code Online (Sandbox Code Playgroud)