Reputation: 3462
I have the definition of the routes as follows
const routes: Routes = [
{
path: '',
component: MyModule,
children:[
{
path: 'path1',
component: MyComponent1,
data: { routeName: "RouteName1" }
},
....
]
},
];
@NgModule({
imports: [RouterModule.forChild(routes)],
exports: [RouterModule]
})
export class MyRoutingModule { }
I would like to obtain the route definition based on url
for the url http://localhost:4200/path1
I'd like to get the object
data: { routeName: "RouteName1" }
The main purpose of this is to display the name of the previous page. I know that I could subscribe to navigation events and keep a history that matches the navigation of the system. But I want to avoid doing that, because the navigation is already being done with history.back and this sometimes can't match
Upvotes: 0
Views: 228
Reputation: 1352
this is the approach summary i used:
routes: any;
constructor(private router: Router) {}
ngOnInit(): void {
this.routes = this.router.config;
const routeName = this.findRouteName();
console.log(routeName);
// this is what you want
}
findRouteName(): string {
let route = window.location.href;
const startIndex = route.lastIndexOf('/') + 1;
const lastIndex = route.length;
route = route.substring(startIndex, lastIndex);
for(const routeConfig of this.routes) {
try {
if (routeConfig.path === route) {
return routeConfig.data.routeName;
}
if (routeConfig.children) {
for (const child of routeConfig.children) {
if (child.path === route) {
return child.data.routeName;
}
}
}
} catch {}
}
return '';
}
Upvotes: 1