In my app-routing.module.ts
file, I have set up the following routes:
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'}
]
Now, in my app.component.ts
file, I am trying to determine the category of each route based on the URL passed:
For example, visiting http://myapp.com/abc/123
should return the category as Public
,
while going to
http://myapp.com/xyz/123/tester/456
should return the category as Private
.
Here is a snippet of my current code:
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)
)
}
However, this code does not correctly identify the route. For instance, when I navigate from http://myapp.com/abc/123
to
http://myapp.com/xyz/123/tester/456
, it still retrieves the data for the previous page http://myapp.com/abc/123
.