在我的应用程序根组件中,我的容器中有一些样式的router-outlet
。
我有路线:
{
path: 'some-path',
component: ChildContainer,
data: { variable:'variable' },
}
我可以在 ChildContainer 中获取变量,但我需要在 AppRoot 中获取它。所以,从 documentation我可以从 child
获取它,但如果我在 AppRoot 构造函数中执行此操作:
const state: RouterState = router.routerState;
const root: ActivatedRoute = state.root;
const child = root.firstChild;
和 console.log(root, child)
- child 为 null,并且 root 包含正确的 child(调用属性 getter)。
那么,如何在 AppRoot 中获取变量
?
最佳答案
您可以点击激活事件来获取路由器导出内实例化组件的引用。
检查这个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!!');
}
}
更新
将ActivatedRoute
公开为公共(public)属性,一旦获得路由组件引用,就可以订阅数据,
onActivate(componentRef){
componentRef.route.data.subsribe(data => {
console.log(data);
});
}
关于javascript - Angular2从应用程序根目录中的子路由获取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42530245/