如何将特性模块的路由声明为另一个组件的子模块?



我正在重构我的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,并且在order-routing.module.ts中导入OrderRoutingModule中定义的路由

,然后你可以更新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
}
]
}
];

主要成分

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

相关内容

  • 没有找到相关文章

最新更新