问题
There have been so many alterations to the Angular router as of late I don't know how to go about this.
I have a param on my parent component called "eventId" which is in the address bar:
http://localhost:4200/event/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
On my purchase plans component, how can I get the eventId?
I've tried:
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
回答1:
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
Available options are:
1. emptyOnly: the default , only inherits parent params for path-less or component-less
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");
}
回答2:
Thanks for all your help. The answer was very lengthy. Without subscription the line was:
this.eventId = this.activatedRoute.parent.snapshot.parent.params.eventId;
来源:https://stackoverflow.com/questions/46935269/get-param-from-parent-component-to-child-component