[英]Angular2 getting data from child route in app-root
In my app-root component I have router-outlet
in container with some styles.在我的 app-root 组件中,我在容器中有一些样式的
router-outlet
。 I have route:我有路线:
{
path: 'some-path',
component: ChildContainer,
data: { variable:'variable' },
}
And I can to get variable in ChildContainer, but I need it in AppRoot.我可以在 ChildContainer 中获取变量,但我需要在 AppRoot 中使用它。 So, from documentation I can get it from
child
, but if I do this in AppRoot constructor:因此,从文档中我可以从
child
获取它,但是如果我在 AppRoot 构造函数中执行此操作:
const state: RouterState = router.routerState;
const root: ActivatedRoute = state.root;
const child = root.firstChild;
and console.log(root, child)
- child is null, and root contains correct child (invoke property getter).和
console.log(root, child)
- child 为 null,root 包含正确的 child(调用属性 getter)。 So, how can I get variable
in AppRoot?那么,如何在 AppRoot 中获取
variable
?
You may tap into activate event to get reference of instantiated component inside the router outlet.您可以点击激活事件以获取路由器插座内实例化组件的引用。
Check This SO question检查这个问题
@Component({
selector: 'my-app',
template: `<h3 class="title">Basic Angular 2</h3>
<router-outlet (activate)="onActivate($event)" ></router-outlet>
`
})
export class AppComponent {
constructor(){}
onActivate(componentRef){
componentRef.sayhello();
}
}
@Component({
selector: 'my-app',
template: `<h3 class="title">Dashboard</h3>
`
})
export class DashboardComponent {
constructor(){}
sayhello(){
console.log('hello!!');
}
}
Update更新
expose ActivatedRoute
as a public property and once you have the routed component reference, subscribe to data,将
ActivatedRoute
作为公共属性公开,一旦获得路由组件引用,就可以订阅数据,
onActivate(componentRef){
componentRef.route.data.subsribe(data => {
console.log(data);
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.