从父组件到子组件获取参数 [英] Get param from parent component to child component
问题描述
最近对Angular路由器进行了很多改动,我不知道该怎么做.
There have been so many alterations to the Angular router as of late I don't know how to go about this.
我在父组件的地址栏中有一个名为"eventId"的参数:
I have a param on my parent component called "eventId" which is in the address bar:
http://localhost:4200/event/1
在这种情况下,其值为1.
In this case it's value is 1.
这是我在路由组件中声明的方式:
Here's how I declare it in the routing component:
{ path: 'event/:eventId', loadChildren: './event/event.module#EventModule', canActivate: [AuthGuard] },
所以我有一个子组件,它位于线下:
So I have a child component which is way down the line:
http://localhost:4200/event/1/event-travel-agents/purchase-plans
在我的购买计划组件上,如何获取eventId?
On my purchase plans component, how can I get the 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);
}
}
但这仅在我处于此级别时有效:
But this only works if I'm at this level:
http://localhost:4200/event/1/event-home
但是,如果我处于这个级别,它将无法正常工作:
But if I'm at this level it won't work:
http://localhost:4200/event/1/event-travel-agents/purchase-plans
推荐答案
在Angular 5.2版本中,有 paramsInheritanceStrategy 的新功能,可以立即帮助您解决问题.
In Angular 5.2 release there is new feature of paramsInheritanceStrategy ,that can help you for your problems now.
您可以按以下方式使用它
You can use it as following
@NgModule({
import :[RouterModule.forRoot(router,{paramsInheritanceStrategy :'always'})]
})
它定义了路由器如何将参数,数据和已解析的数据从父级合并到子级
It defines how the router merges params, data and resolved data from parent to child
可用的选项是:
1..空仅:默认,仅继承无路径或无组件的父参数.
1. emptyOnly: the default , only inherits parent params for path-less or component-less
2. 始终::启用父参数的无条件继承.
2. always: enables unconditional inheritance of parent params.
在组件中,您可以按以下方式使用它:
In component you can use it as follows:
constructor(private route: ActivatedRoute) {}
ngOnInit() {
this.eventId = +this.route.snapshot.paramMap.get("eventId");
}
这篇关于从父组件到子组件获取参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!