【问题标题】:Angular 2 - Use same resolver for parent and child routesAngular 2 - 对父路由和子路由使用相同的解析器
【发布时间】:2016-09-28 09:43:32
【问题描述】:

我有一个 Angular 2.0(稳定版)应用程序,其中一个实体是 project。对于每个projects,我将其详细信息分布在不同的部分/路线中:

  • project/:id/overview
  • project/:id/documents
  • project/:id/logs

project 的 API 在一次调用中返回大部分数据,因此我需要调用一次,并使其可用于不同的子路由。

我的路线如下所示:

export const routing: ModuleWithProviders = RouterModule.forChild([
    { path: 'projects',                   component: ProjectsComponent },
    { path: 'project/new',                component: NewProjectComponent },
    {
        path: 'project/:id',
        component: ProjectDetailComponent,
        resolve: {
            project: ProjectDetailResolve
        },
        children: [
            { path: '', redirectTo: 'overview', pathMatch: 'full' },
            { path: 'overview',           component: ProjectOverviewComponent },
            { path: 'documents',          component: DocumentsComponent },
            { path: 'logs',               component: LogsComponent },
        ]
    }
]);

ProjectDetailComponent当前成功获取项目数据,使用解析器(没有问题):

ngOnInit() {
    this.route.data.forEach((data: { project: any }) => {
        this.project = data.project;
    });
}

但我需要将同一个项目传递给子路由,因为为每个路由触发另一个 API 调用没有意义。

我曾尝试在子组件中使用相同的 ngOnInit 代码,我认为也许 Angular 路由器也会传递路由数据,但没有成功。

有什么想法吗?

谢谢

【问题讨论】:

    标签: angular angular2-routing


    【解决方案1】:

    您可以使用“路由”的“父”属性从父解析器获取数据。

    ngOnInit() {
        this.route.parent.data.subscribe(data => {
            this.project = data.project;
        });
    }
    

    【讨论】:

    • 在当前版本中是否也可以这样做:this.route.parent.snapshot.data['mydata']如果我想要同步访问?
    【解决方案2】:

    取决于组件层次结构的解析对象有多远,您可以通过parentproperty 访问它。

    示例:

    ngOnInit() {
        this.route.parent.data.subscribe(data => this.project = data.project);
    }
    

    或者没有订阅

    ngOnInit() {
        this.project = this.route.snapshot.parent.data['project'];
    }
    

    附: 请记住,如果您的组件比一层更深,您可以无限次链接parent 属性。喜欢this.route.snapshot.parent.parent.data['project']。干杯!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-03-21
      • 2016-12-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-27
      • 2017-12-23
      • 2016-11-25
      相关资源
      最近更新 更多