Jak*_*ake 4 typescript angular-routing angular
我配置了以下路由 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'}
]
Run Code Online (Sandbox Code Playgroud)
在app.component.ts我想根据传递的 URL 获取每个路由的类别:
例如:go to http://myapp.com/abc/123 should return category as Public
going to http://myapp.com/xyz/123/tester/456 should return category asPrivate
这是我到目前为止所拥有的:
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)
)
}
Run Code Online (Sandbox Code Playgroud)
上面的代码似乎没有得到正确的路线。例如:如果我在http://myapp.com/abc/123页面上并导航到http://myapp.com/xyz/123/tester/456,它似乎获取了http://myapp.com/abc/123页面的数据 。
这就是我的应用程序组件中的内容
constructor(private route: ActivatedRoute) {
}
ngOnInit(): void {
this.router.events.pipe(
filter(event => event instanceof NavigationEnd),
map(() => this.rootRoute(this.route)),
filter((route: ActivatedRoute) => route.outlet === 'primary'),
mergeMap((route: ActivatedRoute) => route.data)
).subscribe((event: {[name: string]: any}) => {
this.titleService.setRouteTitle(event['title']);
});
}
private rootRoute(route: ActivatedRoute): ActivatedRoute {
while (route.firstChild) {
route = route.firstChild;
}
return route;
}
Run Code Online (Sandbox Code Playgroud)
我的应用程序路线如下所示:
{ path: 'login', component: LoginComponent, data: { title: 'Login' } }
Run Code Online (Sandbox Code Playgroud)
而我的title service负责设置title。
我和你的唯一区别是你在构造函数中绑定到路由器,而我在ngOnInit. 你能试着调用你所拥有的ngOnInit吗?我不确定这是否会有所作为,但值得一试。
| 归档时间: |
|
| 查看次数: |
1027 次 |
| 最近记录: |