前言
将angular项目打包上架后发现,启动速度是在太慢了,花了十几秒。
默认情况下,在初始化的时候就把所有路由给加载完了,那么多页面,就这样一次性加载完,导致页面加载非常慢,Angular中提出了用懒加载来加载。
通俗的讲就是说进入主模块的时候,子模块不加载,等需要进入子模块的时候才加载。项目划分模块的时候,使用loadChildren
配置路由是最佳选择方案。
关键知识点
1、RouterModule.forRoot() 和 RouterModule.forChild()
RouterModule
对象为提供了两个静态的方法:forRoot()
和forChild()
来配置路由信息。
RouterModule.forRoot()
方法用于在主模块中定义主要的路由信息.
RouterModule.forChild()
与 Router.forRoot()方法类似,但它只能应用在特性模块(子模块)中。
即根模块中使用forRoot()
,子模块中使用forChild()
。
2、懒加载:loadChildren
这里使用到了懒加载LoadChildren
属性。这里没有将对应的模块导入到AppModule
中,而是通过loadChildren
属性,告诉Angular路由依据loadChildren
属性配置的路径去加载对应的模块。这就是模块懒加载功能的具体应用,当用户访问 /xxx/** 路径的时候,才会加载对应的模块,这减少了应用启动时加载资源的大小。
loadChildren的属性值由三部分组成:
需要导入模块的相对路径
#分隔符
导出模块类的名称
懒加载的实现
1、创建项目
ng new angularLaod --routing (生成默认带有routing module 的项目)
执行 --routing会执行以下步骤
创建app-routing.module.ts
将app-routing.module.ts导入到app.module.ts
在app.component.html添加<router-outlet></router-outlet>
2、生成子模块
ng g m childrenLaod --routing
3、在组件中声明component
ng g c children-load/child
在children-load-routing中添加路由默认路径
import {ChildComponent} from './child/child.component';
const routes: Routes = [
{path:'',component:ChildComponent}
];
重复步骤 2、3、4生成children-newload
6、在app-routing.module模块中导入children-load模块
const routes: Routes = [
{path:'',redirectTo:'child'},
{path:'child',loadChildren:'./children-load/children-load.module#ChildrenLoadModule'},
{path:'childNew',loadChildren:'./children-newload/children-newload.module#ChildrenNewloadModule'}
];
注意:LoadChildren必须遵循 相对路径+#+module名称