Angular 传递将数据解析为子路由

标签 angular angular5

我有以下组件结构

  • 项目
    • 编辑项目
    • 子资源1
    • 子资源2
    • 子资源3

所以我的路线是这样的:

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 **/
}

如您所见,我从服务中解析了我的项目数据,并可以通过以下方式在 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}}
    ]
  }
]

但这看起来很丑陋而且是错误的。

最佳答案

这里有两个选择:

1.您可以通过子解析器访问父解析数据,方法是创建特定于子的解析器并访问路由的父属性。

[...模块.ts | ...组件.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. 您可以一起绕过子组件的解析器,并从子组件中访问父数据。

[...模块.ts | ...组件.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;
        });
}

关于 Angular 传递将数据解析为子路由,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48580436/

相关文章:

mongodb - 如何在角度 5 中实现无限滚动分页?

javascript - 如何在 Angular 5 中从 Typescript 调用 JavaScript 函数?

java - 是否可以在没有 Node.js/npm 的情况下创建 Angular 5 Web 应用程序?

Angular 7 :@angular/core/core has no exported member 'OpaqueToken'

javascript - Angular :如何从点击事件获取<li>而不是<ul>

angular - TS1146 : Declaration expected . 。为什么?

angular - 为什么 Ngrx-Effects 不在继承的泛型类中自动订阅

javascript - 难以实现拦截器来处理刷新 token

javascript - Angular 4 语义 UI 选项卡仅在刷新后才起作用

angular - SafeValue 必须使用 [property]=binding :