Angular使用共享布局与特性模块时如何避免布局组件重复创建?
解决方案
你遇到的StartLayoutComponent重复创建问题,本质是根路由和子路由模块中重复定义了path: 'layout'的同组件路由,触发了两次组件实例化,按以下步骤调整即可同时满足三个要求:
步骤1:调整根路由配置
只在AppRoutingModule中定义一次layout路由,预留子路由插槽,不要在其他任何路由模块中重复定义path: 'layout'的路由:
import { NgModule } from '@angular/core'; import { RouterModule, Routes } from '@angular/router'; import { AuthRootComponent } from './auth/authroot/authroot.component'; import { StartLayoutComponent } from './start-layout/start-layout.component'; // 导入各业务模块独立维护的路由配置 import { masterdataRoutes } from './masterdata/masterdata.routes'; import { systemRoutes } from './system/system.routes'; // 其他业务模块路由按需导入 const routes: Routes = [ { path: '', component: AuthRootComponent, }, { path: 'layout', component: StartLayoutComponent, // 合并各业务模块的子路由配置 children: [ ...masterdataRoutes, ...systemRoutes, // 其他模块路由展开即可 ] }, ]; @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule], }) export class AppRoutingModule {}
步骤2:各业务模块独立维护路由配置
在每个业务模块的目录下新建独立的路由配置文件,单独维护本模块下的所有路由规则,不需要引入StartLayoutComponent,也不需要重复定义layout前缀路径:
以masterdata模块为例,新建src/app/masterdata/masterdata.routes.ts:
import { Routes } from '@angular/router'; import { CompanyComponent } from './general/company/company.component'; import { DepartmentComponent } from './general/department/department.component'; // 导入本模块其他组件 // 导出本模块的路由配置供根路由合并 export const masterdataRoutes: Routes = [ { path: 'masterdata/general/company', component: CompanyComponent, // 可单独配置本路由的守卫、数据等属性 }, { path: 'masterdata/general/department', component: DepartmentComponent, }, // 本模块其他路由全部在此维护 ];
如果你的业务模块本身有独立的NgModule,也可以用RouterModule.forChild()在模块内部导入路由,只要保证路由的路径没有加layout前缀,最终都会被合并为layout路由的子路由。
效果验证
- 布局组件不会重复创建:
layout路由全局只定义一次,切换子路由时只会替换内部router-outlet的内容,StartLayoutComponent实例不会销毁重建 - 不需要懒加载:所有业务模块和路由都是同步导入加载,符合你的要求
- 路由配置不会臃肿:各业务模块的路由规则独立维护,根路由只做聚合,不会出现单文件上千行路由配置的问题
内容的提问来源于stack exchange,提问作者derstauner
相关产品推荐
相关产品推荐

