【发布时间】:2020-03-14 18:32:54
【问题描述】:
基本上,我的意图是使用路由参数在同一 Angular (v 9.1) 组件中调用一个函数,用于像 host/:route 这样的路由。
我在app-routing.module.ts有以下路线:
const routes: Routes = [
{ path: ':route', component: AppComponent }
];
同样的 url 导航也有 reload 行为:
@NgModule({
imports: [RouterModule.forRoot(routes,
{
onSameUrlNavigation: 'reload'
})],
exports: [RouterModule]
})
这就是我在ngOnInit 中订阅路由事件的方式:
this.router.events.subscribe((event: Event) => {
if (event instanceof NavigationEnd) {
let route = this.route;
while (route.firstChild) {
route = route.firstChild;
}
if (!this.routeMappginInitialized) {
route.params.subscribe(param => {
if (param.route !== undefined) {
this.mapRouteToNavigation(param.route);
}
});
this.routeMappginInitialized = true;
}
}
});
这确实有效,但我想知道它是否是最佳解决方案,而我使用的大多数 Web 框架都可以轻松访问/映射路由参数。
我也试过了:
this.route.snapshot.paramMap.get('route');
但它总是返回 undefined。
【问题讨论】:
标签: angular typescript angular2-routing