问题
I have routes structured like so:
parent/:id
|
child
|
child
Can I obtain the param from the parent component via:
ngOnInit() {
this.route.params.subscribe((params) => {
this.id = +params['id'];
});
}
and then just attach it as an input on the <router-output> somehow? Or do I have to pull the value from each child the same way I did the parent?
What is the best way to pass the id param from the parent component to all child components?
回答1:
Unfortunately, there is no simple way to access parent route parameters and there is no plans to change it #12767, so the only way is workaround using service or localStorage, whatever you like.
class Service {
public params:Subject<any> = new Subject<any>();
public next(params):void { this.params.next(params); }
}
class Parent {
constructor(service:Service, route:ActivatedRoute){
activatedRoute.params.subscribe(params => service.next(params));
}
}
class Child {
constructor(service:Service){
service.params.subscribe(params => console.log(params));
}
}
Here are some ways that components can intercommunicate: https://angular.io/docs/ts/latest/cookbook/component-communication.html#!#bidirectional-service
回答2:
With Angular router 5 (who knows about 2?), you wouldn't be far ; there is a parent object which is also an ActivatedRoute.
In the child route, you can get it like this:
ngOnInit() {
this.route.parent.params.subscribe(params => {
this.parentRouteId = +params["id"];
console.log(this.parentRouteId);
});
}
And your route must be defined something like that:
const routes: Routes = [
{
path: ':id',
component: MyComponent,
children: [
{ path: '', redirectTo: '/my-page' },
{ path: 'my-page', redirectTo: component: MyChildComponent }
]
},
];
来源:https://stackoverflow.com/questions/42257273/pass-route-param-from-parent-to-child-routes