Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular Router: Get route config that matched the current route

I have the following route configuration in my Angular project:

export const routes: Routes = [
  { path: 'a/:id', loadChildren: './a/a.module#AModule', data: {a: a}},
  { path: 'b/:id',  loadChildren: './b/b.module#BModule', data: {a: b}}
];

Now I can get my route configuration like this:

this.router.config //outputs the above array

The this.router.url shows a, but how would I correctly identify the correct Route since the configuration has the unresolved path and the router holds the resolved path.

The reason I want to do that is to access the data in the app.component where my router-outlet is and not in the component itself (the angular documentation says that the data object is only accessible to the route component itself.

like image 871
moritzg Avatar asked Oct 27 '25 04:10

moritzg


1 Answers

You can use Router.state to get original Route config.

Angular router represents current route as a hierarchical route tree due to children, thus you need to traverse it to get deepest child which is usually what you're looking for.

Can be done in following way:

let currentRoute = this.router.routerState.root;
while (currentRoute.firstChild) {
    currentRoute = currentRoute.firstChild;
}
console.log(currentRoute.routeConfig); // returns `Route` object

In order to react to changes this should be inside this.router.events.subscribe(...).

like image 72
Pavel Gurecki Avatar answered Oct 29 '25 22:10

Pavel Gurecki



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!