【发布时间】:2016-03-31 06:43:54
【问题描述】:
假设我们有带有该模板的 ComponentA:
<div>
<router-outlet></router-outlet>
</div>
ComponentA 有 routeConfig 来路由到 ComponentB。
如何从路由的componentB中获取ComponentA?
我尝试将@Host 注入到 ComponentB,但出现异常。
【问题讨论】:
假设我们有带有该模板的 ComponentA:
<div>
<router-outlet></router-outlet>
</div>
ComponentA 有 routeConfig 来路由到 ComponentB。
如何从路由的componentB中获取ComponentA?
我尝试将@Host 注入到 ComponentB,但出现异常。
【问题讨论】:
路由器使用DynamicComponentLoader 添加组件。这样的组件能力有限(没有@Input()可以通过,@Host()不能用)。
您可以使用共享服务,其中ComponentA 将自己传入,ComponentB 可以读取该值。
Update parent component title from routed child component in Angular 2 此处解释了类似的用例。该服务不必是全球性的。也可以通过将其添加到ComponentA 的providers: [MySharedService] 而不是bootstrap() 来仅在父母和孩子之间共享,如链接答案所示。
【讨论】:
RouterOutlet似乎是一种常见的做法,我自己还没有做过。另一种方法是创建共享服务,注入constructor(router:Router) 并订阅router.subscribe(...) 以获取有关路由更改的通知。