Angular 懒加载的实现

前言

    将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名称

  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值