【发布时间】: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 只会改变