Pass route param from parent to child routes

会有一股神秘感。 提交于 2019-12-10 16:18:22

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!