[英]Get param from parent component to child component
到目前为止,对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
在Angular 5.2版本中,有paramsInheritanceStrategy的新功能,该功能现在可以帮助您解决问题。
您可以按以下方式使用它
@NgModule({
import :[RouterModule.forRoot(router,{paramsInheritanceStrategy :'always'})]
})
它定义了路由器如何将参数,数据和已解析的数据从父级合并到子级
可用的选项有:
1. emptyOnly: default ,仅继承无路径或无组件的父参数
2. 始终:启用父参数的无条件继承。
在组件中,可以按以下方式使用它:
constructor(private route: ActivatedRoute) {}
ngOnInit() {
this.eventId = +this.route.snapshot.paramMap.get("eventId");
}
感谢你的帮助。 答案很冗长。 没有订阅,该行是:
this.eventId = this.activatedRoute.parent.snapshot.parent.params.eventId;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.