【问题标题】:How do I get current route and params from different places in my application?如何从我的应用程序的不同位置获取当前路线和参数?
【发布时间】:2017-06-07 12:08:29
【问题描述】:
在发生路由的组件中(以及路由器出口所在的位置),我可以像往常一样使用 ActivatedRoute,但我有一个组件在路由更改之间保持静态,它需要知道当前路由和路由参数。在 Angular 文档here 中,它说:
你可以从任何地方访问当前的RouterState
使用 Router 服务和 routerState 属性的应用程序。
但我不确定该页面是否解释了如何做到这一点。它没有在任何地方提到 routerState 属性。
【问题讨论】:
标签:
angular
angular2-routing
【解决方案1】:
假设您将ActivatedRoute 注入静态组件:
constructor(private route: ActivatedRoute) {}
然后您可以通过订阅ActivatedRoute 中对应的两个Observable 来收听路由参数或查询参数更改。通过这种方式,静态组件将始终使用最新的路由参数进行更新。
ngOnInit() {
this.route.params.subscribe(params => {console.log(params);});
this.route.queryParams.subscribe(qParams => {console.log(qParams);});
}