简体   繁体   中英

angular - find route definition based on url

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

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 '';
    
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM