【问题标题】:Get param from parent component to child component从父组件获取参数到子组件
【发布时间】:2017-10-25 14:37:18
【问题描述】:

最近对 Angular 路由器进行了如此多的更改,我不知道该怎么做。

我的父组件上有一个名为“eventId”的参数,位于地址栏中:

http://localhost:4200/event/1

在这种情况下,它的值为 1。

这是我在路由组件中声明它的方式:

{ path: 'event/:eventId', loadChildren: './event/event.module#EventModule', canActivate: [AuthGuard] },

所以我有一个子组件:

http://localhost:4200/event/1/event-travel-agents/purchase-plans

在我的购买计划组件中,如何获取 eventId?

我试过了:

import { ActivatedRoute } from '@angular/router';
export class PurchasePlansComponent implements OnInit {
  eventId: number;
  constructor(private activatedRoute: ActivatedRoute) {
    this.subscription = activatedRoute.parent.params.subscribe(
      (param: any) => {
        this.eventId = param['eventId'];
      }
    );
  }
  ngOnInit() {
    alert(this.eventId);
  }
}

但这只有在我处于这个级别时才有效:

http://localhost:4200/event/1/event-home

但如果我在这个级别,它就行不通了:

http://localhost:4200/event/1/event-travel-agents/purchase-plans

【问题讨论】:

  • (目前无法测试,只是给您一个想法)您是否尝试过类似:activatedRoute.snapshot.parent.params['eventId']
  • @deezg 使用快照不适用于参数动态更改的场景,您需要订阅更改
  • @RahulSingh 为什么它不起作用?我没有看到任何暗示他的组件被重用的东西。还是我错过了什么?
  • @deezg 他正在寻找该特定参数的事件 id,我猜,事件 id 只会改变

标签: angular angular-router


【解决方案1】:

在 Angular 5.2 版本中有 paramsInheritanceStrategy 的新功能,现在可以帮助您解决问题。

你可以如下使用它

@NgModule({
    import :[RouterModule.forRoot(router,{paramsInheritanceStrategy :'always'})]
})

它定义了路由器如何将参数、数据和解析数据从父级合并到子级

可用选项有:

1. emptyOnly: 默认,仅继承无路径或无组件的父参数

2. always:启用父参数的无条件继承。

在组件中可以如下使用:

 constructor(private route: ActivatedRoute) {}

 ngOnInit() {
    this.eventId = +this.route.snapshot.paramMap.get("eventId");
  }

【讨论】:

    【解决方案2】:

    感谢您的所有帮助。 答案很长。没有订阅该行是:

    this.eventId = this.activatedRoute.parent.snapshot.parent.params.eventId;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-03-31
      • 1970-01-01
      • 1970-01-01
      • 2019-05-05
      • 1970-01-01
      • 1970-01-01
      • 2017-08-14
      • 2020-09-01
      相关资源
      最近更新 更多