Get route parameters in component

蓝咒 提交于 2019-11-30 09:02:39

问题


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
      }
    ]
  }
];

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

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>

回答1:


Create a service (let's call it RouteParamsService) :

export class RouteParamsService {
  innovationTrackId = new BehaviorSubject(undefined);
}

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.




回答2:


Use Activated Route. As index of the params array you can use any parameter name.

constructor(private itunes:SearchService,
    private route: ActivatedRoute) {

    this.route.params.subscribe( params => params[<any parameter name>]); 
}


来源:https://stackoverflow.com/questions/51943663/get-route-parameters-in-component

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!