【发布时间】:2020-02-17 20:05:33
【问题描述】:
我在app-routing.module.ts中配置了以下路由
const routes: Routes = [
{
path: 'abc/:id', component: AbcComponent, data: { category: 'Public' }
},
{
path: 'xyz/:id/tester/:mapId', component: XyzComponent, data: { category: 'Private' }
},
{ path: '**', redirectTo: '/page-not-found', pathMatch: 'full'}
]
在app.component.ts我想根据传递的URL获取每个Route的类别:
例如:转到http://myapp.com/abc/123 应返回类别为Public
去http://myapp.com/xyz/123/tester/456 应该返回类别为Private
这是我目前所拥有的:
constructor(
private activatedRoute: ActivatedRoute,
private router: Router
)
{
checkRouteAndGetCategory()
}
checkRouteAndGetCategory()
{
this.router.events.pipe(
filter(event => event instanceof NavigationEnd),
map(() => this.activatedRoute),
map(route => {
while (route.firstChild) route = route.firstChild
return route
}),
filter(route => route.outlet === 'primary'),
mergeMap(route => route.data)
).subscribe(data =>
console.log('data', data)
)
}
上面的代码似乎没有找到正确的路线。例如:如果我在http://myapp.com/abc/123 页面上并导航到http://myapp.com/xyz/123/tester/456,它似乎获得了http://myapp.com/abc/123 页面的数据。
【问题讨论】:
标签: angular typescript angular-routing