将路线参数从父路线传递到子路线 [英] Pass route param from parent to child routes

查看:136
本文介绍了将路线参数从父路线传递到子路线的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的路线结构如下:

parent/:id
    |
    child
    |
    child

我可以通过以下方式从父组件中获取参数:

Can I obtain the param from the parent component via:

ngOnInit() {
  this.route.params.subscribe((params) => {
      this.id = +params['id'];
  });
}

,然后以某种方式将其作为输入附加到<router-output>上?还是我必须像处理父母一样从每个孩子那里提取价值?

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?

id参数从父组件传递到所有子组件的最佳方法是什么?

What is the best way to pass the id param from the parent component to all child components?

推荐答案

不幸的是,没有简单的方法来访问父级路由参数,也没有计划对其进行更改

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));
        }
   }

以下是组件可以相互通信的一些方式: https://angular.io/docs/ts/latest/cookbook/component-communication.html#!#bidirectional-service

Here are some ways that components can intercommunicate: https://angular.io/docs/ts/latest/cookbook/component-communication.html#!#bidirectional-service

这篇关于将路线参数从父路线传递到子路线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆