使用路由延迟加载 Angular 模块
来源:互联网 发布:md5加盐加密java代码 编辑:程序博客网 时间:2024/06/14 22:40
Angular 非常模块化,模块化的一个非常有用的特性就是模块作为延迟加载点。延迟加载意味着可以在后台加载一个模块和其包含的所有组件等资源。这样 Angular 就不需要在第一个界面从服务器下载所有的文件,直到您请求它,才下载相应的模块。这对提供性能和减少首屏的初始下载文件尺寸有巨大的帮助。而且它可以很容易设置。
这里将使用一个简单示例来演示这个特性是如何工作的。将应用拆分为多个不同的模块,可以在需要的时候再进行延迟加载。
延迟加载的路由需要在根模块之外定义,所以,你需要将需要延迟加载的功能包含在功能模块中。
我们使用 Angular CLI 来创建一个演示项目:Demo.
ng new demo
然后,进入到 demo 文件夹中。安装必要的 package。
npm i
在安装之后,我们创建一个新的模块 shop。在 angular CLI 中,ng 是命令提示指令,g 表示 generate,用来创建某类新 item。
创建新的名为 shop 的模块就是:
ng g module shop
这会导致在 Angular 项目的 src/app 文件下创建一个新的文件夹,并添加一个名为 shop.module.ts 的模块定义文件。
然后,我们在默认的 app 模块和新创建的 shop 模块中分别创建组件。
ng g c home/homeng g c shop/cartng g c shop/checkout ng g c shop/confirm
CLI 会将 home 分配到 app 模块中,将 cart、checkout、confirm 分配到 shop 模块中,比如,
此时的 shop.module.ts 内容如下:
import { NgModule } from '@angular/core';import { CommonModule } from '@angular/common';import { CheckoutComponent } from './checkout/checkout.component';import { CartComponent } from './cart/cart.component';import { ConfirmComponent } from './confirm/confirm.component';@NgModule({ imports: [ CommonModule ], declarations: [CheckoutComponent, CartComponent, ConfirmComponent]})export class ShopModule { }
修改根组件
Angular CLI 默认生成的 app.component.ts 组件是应用的主页面,其中包含了一些关于 Angular 的介绍信息,我们将它修改成我们需要的内容。将默认生成的 app.component.html 内容修改为如下内容。
<!--The content below is only a placeholder and can be replaced.--><h1>Lazy Load Module</h1><a [routerLink]="['/shop']" >Shop Cart</a><router-outlet></router-outlet>
这里提供了一个占位的 router-outlet,各个组件将显示在这里面。
同时,提供了一个导航链接,可以直接导航到 /shop/cart 组件。
创建路由
根路由
首先创建根路由。
我们在 app 文件夹中,添加一个名为 main.routing.ts 的路由配置文件。内容如下:
import { Routes } from '@angular/router';// HomeComponent this components will be eager loadedimport { HomeComponent } from './home/home.component';export const routes: Routes = [ { path: '', component: HomeComponent, pathMatch: 'full' }, { path: 'shop', loadChildren: './shop/shop.module#ShopModule' }, { path: '**', component: HomeComponent }];
其中,home 组件是正常的提前加载。
需要注意的是一下几点:
- 我们使用了 loadChildren 来延迟加载一个模块。而不是使用提前加载所使用的 component。
- 我们使用了一个字符串而不是符号来避免提前加载。
- 我们不仅定义了模块的路径,还提供了模块的类名。
在 app.module.ts 中启用根路由。主要需要使用 forRoot 来启用根路由。
- 使用路由延迟加载 Angular 模块
- 使用路由延迟加载 Angular 模块
- Angular延迟加载
- angular模块加载
- angular路由的使用
- (六)使用angular.bootstrap完成模块的手动加载
- angular使用requirejs/ui-router/angularAMD实现动态加载模块
- 使用angular.bootstrap完成模块的手动加载
- 使用angular.bootstrap完成模块的手动加载
- angular中的路由简单使用
- angular路由的使用案例
- 用angular $httpProvider做路由加载遮罩层
- Angular从普通路由到惰性加载
- angular路由 和过滤器分页加载数据
- Angular+Requirejs实现模块按需加载
- angular共享模块的使用
- angular 路由
- angular路由
- AJAX 跨域请求
- 【面向JS--字符串】
- centos7网卡不能重启
- hibernate中对象的状态有三种
- tomcat配置https方法
- 使用路由延迟加载 Angular 模块
- 创建基于 AFS 的 Docker 容器卷
- pthread_join与pthread_detach详解(转)
- Loading... 算法
- eclipse 生成javadoc文档 jdk
- 在子查询中使用 order by 总是告错:ORA-00907: missing right parenth.解决办法!
- 通过反射获取类的基本结构
- 创建型设计-建造者模式
- 猴子选大王问题