是否可以通过某种方式从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 }
];
答案 0 :(得分:0)
无法从您的根组件访问路由参数(它没有路由)。
我可以想到两种解决方案:
ngOnInit() {
this.router.events
.pipe(
filter(e => e instanceof NavigationEnd),
map((e: NavigationEnd) => e.urlAfterRedirects),
// parse the url as needed
)
.subscribe();
}
创建一个存储当前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))