# Angular路由惰性加载实例运用 懒加载路由配置 提升加载速度 优化用户体验

> 在angular实际项目应用中，随着业务需求的不断增加，难免整个项目模块变的比较庞大，致使在首次加载过程中比较耗时，等待时间过长影响用户体验；因此呢，我们就需要运用angular中的惰性加载路由配置使其按需加载，也就是说，当我们导航到该路由时再对其动态加载。

Author: DeathGhost
Published: 2018-07-30 20:55:15
Category: angular
Canonical: https://www.deathghost.cn/article/angular/29
Keywords: angular, 惰性加载, 懒加载, 延迟加载, 提升加载速度, angular组件加载, angular2 路由加载, angular6.x路由惰性加载

angular 惰性加载目的在于提升页面组件渲染速度，便于用户快速访问操作；同时呢，在开发过程中避免太多引入搞不灵清，不便管理；工作中往往都是团队来完成项目，少则也2-3人，随着项目的不断成长，可能后续二次修改或查看起来都比较费劲；所以，在这里我将其作以笔记，可供参考。

![Angular路由惰性加载实例运用 懒加载路由配置 提升加载速度 优化用户体验](https://www.deathghost.cn/public/upload/article/2018/07/1534340536832.jpg)

Angular路由惰性加载实例运用 懒加载路由配置 提升加载速度 优化用户体验

我们在拿到项目首先对其功能模块划分，了解产品需求，便于我们预先架设好每个模块，当然了，后期也可以返回来修改，都一样。

angular我接触时间也不长，看了好久，一直也应用到，所以一些功能操作也没对其配置测试，今天按项目的需求而言，稍微有点小多及上个项目打包后发布服务器第一次打开速度是相当的慢（一次性加载所有组件）也难怪；于是今天看了下，做了个小测试，在此将其分享记录下来。

这里直接说惰性加载这块，至于其他路由模块分离，直接创建module导入组件导出路由模块即可；刚接触我是被绕晕了，所以在这里理一理，只需要记住这几个点就可以了：

forRoot与forChild简单知道下，forRoot用于根模块加载路由，forChild用于子模块加载路由就可以了；另外一个就是loadChildren属性（注意不是 children 属性），把它设置为模块的路径地址且加上# 分隔符同时加上导出模块的类名即可。

## 操作方法

某项目模块需要惰性加载时，通过命令执行，先创建模块。

eg: ng g m pages/test-lazy // test-lazy.module.ts
接下来再创建一个该模块的路由模块。

... // test-lazy-routing.module.ts
然后在此文件夹下创建组件

eg: ng g c pages/test-lazy/test-lazy --spec=false
// ...test-lazy.component （ts,html,css）
如果有子集的话，按上述方法在其文件夹下继续创建

eg: ng g c pages/test-lazy/child --spec=false
最终文件结构如下所示：

test-lazy
    ------ child // ...
    ------ test-lazy.component.css
    ------ test-lazy.component.html
    ------ test-lazy.component.ts
    ------ test-lazy.module.ts
    ------ test-lazy-routing.module.ts
里面的代码内容，如同我们刚使用Angular时一样，导入组件，导出路由。

test-lazy.module.ts
import { TestLazyRoutingModule } from './test-lazy-routing.module';
import { TestLazyComponent } from './test-lazy.component';
import { ChildComponent } from './child/child.component';

@NgModule({
  imports: [
    TestLazyRoutingModule
  ],
  declarations: [TestLazyComponent, ChildComponent]
})
export class TestLazyModule { }
test-lazy-routing.module.ts
import { TestLazyComponent } from './test-lazy.component';
import { ChildComponent } from './child/child.component';
@NgModule({
  imports: [
    RouterModule.forChild([
      {
        path: '',
        component: TestLazyComponent,
        children: [{path: 'child', component: ChildComponent}]
      }
    ])
  ],
  exports: [RouterModule]
})
export class TestLazyRoutingModule { }
最后呢，在根路由中添加导入路由，注意标注的地方。

RouterModule.forRoot([
    {
        path: '',
        component: FullComponent,
        children: [
            {path: '', redirectTo: 'login', pathMatch: 'full'},
            {path: 'login', component: LoginComponent}
        ]
    },
    {
        path: 'admin',
        component: MainComponent,
        children: [
            {path: '', redirectTo: 'index', pathMatch: 'full', data: {title: '仪表盘', module: 'index', keep: true}},
            {path: 'index', component: IndexComponent, data: { title: '仪表盘', module: 'index', keep: true}},
            {path: 'testLazy', loadChildren: './test-lazy/test-lazy.module#TestLazyModule', data: { title: '懒加载', module: 'testLazy', keep: true}},

            {path: '**', component: NotFoundComponent, data: { title: '404', module: '**', keep: true}}
        ]
    },
    {path: '**', component: NotFoundComponent}
])
这样就操作完毕，当路由器导航到这个路由时，它会用 loadChildren 字符串来动态加载；惰性加载和重新配置工作只会发生一次，也就是在该路由首次被请求时。在后续的请求中，该模块和路由都是立即可用的。

## Related

- Previous: [Angular 路由快照 使用RouteReuseStrategy路由复用策略暂存路由状态](https://www.deathghost.cn/article/angular/28)
- Next: [Angular自定义预加载策略](https://www.deathghost.cn/article/angular/88)
