获取组件中的路由参数 [英] Get route parameters in component
问题描述
我正在处理 Angular-6 项目.我的应用程序有很多子路由.其中之一如下:
I am working on the Angular-6 project. I have many child routes for my application. One of them is as follow:
const routes: Routes = [
{
path: 'innovation-track/:innovation-track-id', component: InnovationTrackComponent,
children: [
{
path: 'sprint', component: ScrumBoardComponent
}
]
}
];
我想从我的 ScrumBoardComponent 中的 URL 获取 innovation-track-id 值.
I want to get innovation-track-id value from URL in my ScrumBoardComponent.
我知道我可以通过执行以下操作来获得它:
I know I can get this by doing following:
constructor(private _route: ActivatedRoute) { }
//somewhere in method
this._route.snapshot.parent.paramMap
但是,我想在任何组件中获取 innovation-track-id 值,不管它是子组件还是父组件.我的意思是我不想做以下事情:
But, I want to fetch innovation-track-id value in any component, doesn't matter if it is child or parent. What I mean is I don't want to do the following:
this._route.snapshot.parent.paramMap
相反,我想做以下事情:
Instead, I want to do something as following:
this._route.params.<any parameter name>
推荐答案
创建一个服务(我们称之为RouteParamsService
):
Create a service (let's call it RouteParamsService
) :
export class RouteParamsService {
innovationTrackId = new BehaviorSubject(undefined);
}
在你的父组件中,订阅 params :
In your parent component, subscribe to params :
constructor(private route: ActivatedRoute, private service: RouteParamsService) {
route.params
.subscribe(params => service.innovationTrackId
.next(params && params['innovation-track-id'] || undefined))
}
现在您可以在任何组件中订阅您的服务,您将获得参数的值.父组件将处理任何值更改,并且服务会将更改传播到订阅它的任何组件.
Now you can subscribe to your service in any component, and you will get the value of your param. The parent component will handle any value change, and the service will propagate the change to any component that subscribed to it.
这篇关于获取组件中的路由参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!