从当前模块获取所有路由 - Angular 2

Getting all routes from current module - Angular 2

嗨,我在我的示例中使用延迟加载。

export const appRoutes: Routes = [

    { path: 'comp1', loadChildren: 'app/components/comp1/comp1.module#comp1Module' },
   { path: 'comp2', loadChildren: 'app/components/comp2/comp2.module#comp2Module' },
. . .

]

comp1Module 具有以下子路由

export const comp1Routes: Routes = [
   { path: 'comp1/default', component: DefaultComponent },
 ];

在路由时我需要从模块中获取所有路由。

例如:我想从模块 comp1

获取所有路由

您可以通过注入路由器并拉取配置来使用router.config。

constructor(private router: Router){
  console.log(this.router.config);
}

我使用这种方法:

将您的延迟加载模块路由定义为根组件的子组件:

const routes: Routes = [
    { path: '', component: LazyLoadedRootComponent,
        children: [
            { path: 'child1', component: Child1Component },
            { path: 'child2', component: Child2Component },
        ]
    }
];

@NgModule({
  declarations: [LazyLoadedRootComponent, Child1Component, Child2Component],
  imports: [
    CommonModule,
    RouterModule.forChild(routes)
  ]
})
export class LazyLoadedModule { }

然后从你的根模块组件你可以像这样得到它的子路由:

export class LazyLoadedRootComponent implements OnInit {

    constructor(private route: ActivatedRoute) {
    }

    ngOnInit(): void {
        console.log(this.route.routeConfig.children);
    }
}