获取组件中的路线参数 [英] Get route parameters in component

查看:107
本文介绍了获取组件中的路线参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在从事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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆