如何将功能模块的路由声明为另一个组件的子级?

How to declare routes of feature module as children of another component?

我正在重构我的 Angular 应用程序。我的app-routing.module.ts有两条主要路线:

const routes: Routes = [
  {path: "login", component: LoginComponent, canActivate: [IsNotLoggedGuard]},
   {path: "", component: MainComponent, canActivate: [AuthGuard],children: [
    {path: "orders", component: OrderComponent, children:[...]
   ]},
  
];

现在,我为新创建的OrderModule

创建了一个路由模块
// in order-routing.module.ts
const routes = [
    {path: "orders", component: OrderComponent, children:[...]
]

现在我可以删除 app-routing.module.ts

中的路线
const routes: Routes = [
  {path: "login", component: LoginComponent, canActivate: [IsNotLoggedGuard]},
   {path: "", component: MainComponent, canActivate: [AuthGuard],children: []},
  
];

但是在 MainComponent 中我有一个 <router-outlet></router-outlet 我想在其中加载所有功能组件但是因此我必须以某种方式将路由声明为子路由但是如果我有我该怎么做每个功能模块有多个路由模块?

假设您在 order.module.ts 中有一个 OrderModule 并在其中导入 OrderRoutingModule 并使用 order-routing.module.ts

中定义的路由

然后您可以更新 app-routing.module.ts 以像这样延迟加载该模块:

// in order-routing.module.ts
const routes: Routes = [
  {path: "login", component: LoginComponent, canActivate: [IsNotLoggedGuard]},
   {
      path: "", 
      component: MainComponent, 
      canActivate: [AuthGuard],
      loadChildren: () => import('../order/order.module').then((m) => m.OrderModule)
    },
  
];

利用lazy-loading,这些功能模块将在用户到达特定路线时加载。

app-routing.module.ts

const orderModule = () => import('..../order.module.ts').then(m => m.OrderModule);
const otherFeatureModule = () => import('.../feature1.module').then(m => m.FeatureModule);

const routes: Routes = [
  {
     path: "login", 
     component: LoginComponent, 
     canActivate: [IsNotLoggedGuard]
  },
  {  path: "", 
     component: MainComponent, 
     canActivate: [AuthGuard],
     children: [
       {
         path: 'order', 
         loadChildren: orderModule
       },
       {
         path: 'feature1',
         loadChildren: otherFeatureModule
       }
     ]
  }
];

main-component

<!-- your main content -->
<router-outlet></router-outlet> // here will be displayed 
                                // order and other features 
                                // components