Перечислите все вложенные дочерние маршруты в Angular7 - PullRequest
1 голос
/ 09 апреля 2019

У меня есть приложение Angular 7 с корневым app-routing.module.ts с двумя маршрутами.

Есть несколько под-маршрутов, в которых приложение route является родительским, а также есть некоторые другие модули маршрутизации, у которых также есть дочерние элементы.

Я уже использую и настроил ответ Адриана Пола на приведенный ниже вопрос, и это работает, когда у меня только один слой детей, но не работает с несколькими слоями: https://stackoverflow.com/a/53208406/10928399

приложение-routing.module.ts

const routes: Routes = [
  {
    path: 'login',
    loadChildren: './../../login.module#LoginModule'
  },
  {
    path: '',
    loadChildren: './../layout.module#LayoutModule',
    canActivate: [AuthGuard]
  }
];

топологий routing.module.ts

const routes: Routes = [
  {
    path: '',
    component: LayoutComponent,
    children: [
      {
        path: '',
        redirectTo: 'some-route',
        pathMatch: 'full'
      },
      {
        path: 'some-component',
        loadChildren: './some-component/some-component-layout.module#SomeComponentLayoutModule',
        canActivate: [AuthGuard],
        data: {
          label: 'Some Component'
        }
      },
      {
        path: 'some-other-component',
        loadChildren: './some-other-component/some-other-component.module#SomeOtherComponentModule',
        canActivate: [AuthGuard],
        data: {
          label: 'Some Other Component'
        }
      }
    ]
  }
];

некоторые-другие-компонентные-routing.module.ts

const routes: Routes = [
  {
    path: '',
    component: MultiReaderConfigurationViewComponent,
    children: [
      {
        path: '',
        redirectTo: 'child'
      },
      {
        path: 'child',
        component: ChildComponent,
        canActivate: [AuthGuard],
        resolve: [ChildService],
        data: {
          label: 'Child'
        }
      },
      {
        path: 'child2',
        component: Child2Component,
        canActivate: [AuthGuard],
        resolve: [Child2Service],
        data: {
          label: 'Child2'
        }
      }
    ]
  }
];

Вот как я «обновил» код из вышеупомянутого ответа, чтобы добраться до дочерних маршрутов, но я думаю, что это довольно уродливо и неэффективно, если я хочу пойти глубже:

private getMenusFromRouterConfig(menus: IMenuItem[], parent: string, routes: Route[]): void {
    for (let menuIndex = 0; menuIndex < routes.length; menuIndex++) {
      const route = routes[menuIndex];
      const routerConfig: LoadedRouterConfig = (route as any)._loadedConfig;
      const fullPath = this.getFullPath(parent, route.path);
      const children: IMenuItem[] = [];

      if (route.data && route.loadChildren && route.loadChildren.length > 0) {
        this.pushItemsToMenu(children, menus, menuIndex, route);
      }

      if (route.children) {
        this.getMenusFromRouterConfig(menus, fullPath, route.children);
      }

      if (route.loadChildren && route.loadChildren.length > 0 && routerConfig) {
        this.getMenusFromRouterConfig(menus, fullPath, routerConfig.routes);
      }
    }
  }

  private getFullPath(parent: string, path: string): string {
    return parent + '/' + path;
  }

  private pushItemsToMenu(childArray: IMenuItem[], menus: IMenuItem[], menuIndex: number, route: Route): void {
    const routerConfig: LoadedRouterConfig = (route as any)._loadedConfig;
    const menuPath = route.path;
    const children: IMenuItem[] = [];

    if (routerConfig) {
      routerConfig.routes.filter(x => x.data && x.data.label).forEach((child, idx) => {

        childArray.push({
          id: idx,
          label: child.data.label,
          routerLink: this.getFullPath('/' + menuPath, child.path),
          children
        });
      });

      routerConfig.routes.filter(x => x.children).forEach(element => element.children.filter(x => x.data && x.data.label).forEach((child, idx) => {
        childArray.push({
          id: idx,
          label: child.data.label,
          routerLink: this.getFullPath('/' + menuPath, child.path)
        });
      }));
    }

    menus.push({
      id: menuIndex,
      label: route.data.label,
      routerLink: '/' + menuPath,
      children: childArray
    });
  }

Любая помощь или совет приветствуется.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...