如何在应用程序组件中获取URL参数

时间:2018-10-08 16:24:23

标签: angular typescript

是否可以通过某种方式从ApplicationComponent中获取英雄ID参数?

const appRoutes: Routes = [
  { path: 'crisis-center', component: CrisisListComponent },
  { path: 'hero/:id',      component: HeroDetailComponent },
  {
    path: 'heroes',
    component: HeroListComponent,
    data: { title: 'Heroes List' }
  },
  { path: '',
    redirectTo: '/heroes',
    pathMatch: 'full'
  },
  { path: '**', component: PageNotFoundComponent }
];

2 个答案:

答案 0 :(得分:0)

无法从您的根组件访问路由参数(它没有路由)。

我可以想到两种解决方案:

1。自己解析(不是很健壮)

ngOnInit() {
  this.router.events
    .pipe(
      filter(e => e instanceof NavigationEnd),
      map((e: NavigationEnd) => e.urlAfterRedirects),
      // parse the url as needed
    )
    .subscribe();
}

2。在专用服务中共享参数(更多努力)

创建一个存储当前ID的服务(在示例RouteParamsService中)。然后访问您的AppComponent中的ID。

HeroComponent

constructor(private route: ActivatedRoute,
            private paramsService: RouteParamsService) {
}

ngOnInit() {
  this.route.paramMap.subscribe(params => this.paramsService.set('heroId', params.get('id')));
}

ngOnDestroy() {
  this.paramsService.delete('heroId');
}

AppComponent

constructor(private paramsService: RouteParamsService) {
}

ngOnInit() {
  this.paramsService.params.subscribe(params => params['heroId']);
}

答案 1 :(得分:0)

返回一个包含网址标识符的数组

console.log(window.location.pathname.match(/(\d+)/g))
console.log('questions/52706460/how-to-obtain-a-url-parameter-in-the-application-component'.match(/(\d+)/g))