Home >Web Front-end >JS Tutorial >Understand the concepts related to angular10 modules and get started quickly!
This article will give you an understanding of the modules in angular10, and introduce the module composition, ngModule attributes, commonly used modules, the difference between angualr modules and js modules, and lazy loading of modules. Let’s take a look. .
NgModule module is an important point in Angular, because the basic building block of Angular is NgModule. NgModule will collect related codes (components, instructions, services) into some functional sets to form functional units. It can be said that modules provide a compilation context for components, instructions, and services. [Related tutorial recommendations: "angularTutorial"]
When using the Angular CL command to create a new project, a root module will be generated for us, named AppModule. The root module has a root Component AppComponent, guide this root module to start the application. Angular applications are modular. During development, we will establish various large and small modules according to their functions, functions, and characteristics to build it into an application. Any module can contain any number of other components.
The angular module is a class with an @ngModule() decorator, and the decorator @ngModule accepts a metadata object. The properties of this object are used to describe the module.
import { BrowserModule } from '@angular/platform-browser'; //从主模块中引入NgModule(模块装饰器或模块注解) import { NgModule } from '@angular/core'; //引入组件,因为模块为组件提供编译的上下文环境 import { AppComponent } from './app.component'; // 引入路由模块 import { AppRoutingModule } from './app-routing.module'; //装饰器以json的形式声明元数据 @NgModule({ //组合模块的组件和管道 declarations: [ AppComponent ], //模块依赖项 imports: [ BrowserModule,AppRoutingModule ], //子模块可以输入导出的模块 imports: [], //模块提供的服务 providers: [], //指定宿主组件,只在根模块中出现 bootstrap: [AppComponent] }) export class AppModule { }
Click in @NgModule() We can see the class of the decorator He has the following attributes and official explanations of his attributes.
export declare interface NgModule { providers?: Provider[];// 本模块向全局服务中贡献的那些服务的创建器。 这些服务能被本应用中的任何部分使用。(你也可以在组件级别指定服务提供商,这通常是首选方式。) declarations?: Array<Type<any> | any[]>;// 那些属于本 NgModule 的组件、指令、管道 imports?: Array<Type<any> | ModuleWithProviders<{}> | any[]>;// 那些导出了本模块中的组件模板所需的类的其它模块 exports?: Array<Type<any> | any[]>;//那些能在其它模块的组件模板中使用的可声明对象的子集 entryComponents?: Array<Type<any> | any[]>; bootstrap?: Array<Type<any> | any[]>; schemas?: Array<SchemaMetadata | any[]>; }
providers: All the services injected in the component of this module are here Define it in advance, otherwise there will be an error message when using this service in this module.
declaration: declaration means declaration in English. Declare some components, instructions, pipes, etc. to be used in some modules here.
imports: Import some modules. For example, if I combine all instructions into a module, when I use some of the instructions, I can choose to import the entire instruction module. You can also import some modules installed through npm install before they can be used.
exports: Export components or instruction pipelines, etc., so that modules that reference this module can use the components or instruction pipelines of this module.
exporyComponents: entry component represents the entry component of angular. The bootable component is an entry component, and Angular will load it into the DOM during the boot process. Other entry components are dynamically loaded at other times. Literal meaning, but when to use it, for example, if I want to pop up a component, then this component needs to be dynamically loaded into the DOM. At this time, the component xxxComponent needs to be written.
bootstrap: The component that should be started when this module is started. From the above code, you can see that AppModule is the startup component of the root module.
schemas: Elements or attributes that do not belong to Angular components or directives need to be declared here.
NgModule | Import | Use |
---|---|---|
BrowserModule | @angular/platform-browser | When you want to run the application in the browser |
CommonModule | @angular/common | When you want to use NgIf and NgFor |
FormsModule | @angular/forms | When you want to build a template driven form (it contains NgModel) |
ReactiveFormsModule | @angular/forms | When you want to build a responsive form |
RouterModule | @angular/router | To use the routing function, and you need to use RouterLink ,.forRoot() and .forChild() |
HttpClientModule | @angular/common/http | When you want to talk to the server |
ng generate module <module-name> //创建一个模块 ng g m <module-name> // 缩写 ng g m order // 创建订单模块 ng g m order --routing // 创建带路由订单模块
js模块(ES6 中的模块)
模块功能主要由两个命令构成:export和import,export命令用于规定模块的对外接口,import命令用于输入其他模块提供的功能
一般来说,一个模块就是一个独立的文件,该文件内部的所有变量,外部无法获取,如果你希望外部能够读取模块内部的某个变量,就必须使用export关键字输出该变量
// profile.js export var firstName = 'Michael'; export var lastName = 'Jackson'; export var year = 1958; // 优先考虑下面写法 var firstName = 'Michael'; var lastName = 'Jackson'; var year = 1958; export {firstName,lastName, year}
export 命令除了可以导出变量,还可以导出函数和类(class)
function a () {...} function b () {...} export { a, b as b_ // 通过as关键字重命名对外接口 }
使用export命令定义了模块的对外接口后,其他js文件就可以通过import命令来加载这个模块了。
// main.js import {firstName, lastName, year} from './profile.js'; function setName(element) { element.textContent = firstName + ' ' + lastName; }
import命令接受一对大括号,里面指定要从其他模块导入的变量名。大括号里面的变量名,必须与被导入模块(profile.js)对外接口的名称相同
我们也可以对加载的模块进行重命名
import { lastName as surname } from './profile.js';
除了指定加载某个输出值,还可以使用整体加载,即用星号(*)指定一个对象,所有输出值都加载在这个对象上面
// circle.js export function area(radius) { return Math.PI * radius * radius; } export function circumference(radius) { return 2 * Math.PI * radius; } // 使用 import * as circle from './circle'; console.log('圆面积:' + circle.area(4)); console.log('圆周长:' + circle.circumference(14))
这里有一个地方需要注意,模块整体加载所在的那个对象(上例是circle),应该是可以静态分析的,所以不允许运行时改变,下面的写法都是不允许的
import * as circle from './circle'; // 下面两行都是不允许的 circle.foo = 'hello'; circle.area = function () {};
angualr模块
angualr模块在文章开头有作介绍(angualr模块概述和angualr模块构成)
NgModule 类 与 JavaScript 模块有下列关键性的不同:
相比之下我们可以看出,NgModule模块更灵活,扩展性强,更具优势。
如果我们将所有的模块都导入根模块,那么应用在初始化加载的时候就会非常慢。这时候我们应该考虑使用惰性加载。根据需求加载相应都模块,减少应用初始化包的大小以及减少加载的时间,提高用户体验性。
惰性加载的模块特点是该模块拥有路由模块。因此 接着上面我们创建了一个订单模块 我们给订单模块加上路由。并再创建一个user.module以及user.module模块下的list组件。
ng g m user --routing //创建user模块 ng g c user/list --skip-tests //在user模块里面创建组件list
<!--order.module 订单模块--> import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; //为一些结构性指令提供支持 import { OrderRoutingModule } from './order-routing.module'; //模块具有自己的路由 import { ListComponent } from './list/list.component'; //引入list组件 @NgModule({ declarations: [ListComponent], imports: [ CommonModule, OrderRoutingModule ] }) export class OrderModule { }
配置子路由
<!--order-routing.module 订单模块对应的路由模块--> import { NgModule } from '@angular/core'; import { Routes, RouterModule } from '@angular/router'; import { ListComponent } from './list/list.component'; const routes: Routes = [ //子路由的组件配置 { path: 'list', component: ListComponent }, ]; @NgModule({ imports: [RouterModule.forChild(routes)], exports: [RouterModule] }) export class OrderRoutingModule { }
user模块如此类推
配置总路由(重点,掌握)
<!--AppRoutingModule 根路由模块--> import { NgModule } from '@angular/core'; import { Routes, RouterModule } from '@angular/router'; const routes: Routes = [ //根路由的配置 { path: 'orders', loadChildren: './order/order.module#OrderModule' // 配置订单子模块 }, { path: 'users', loadChildren: './user/user.module#UserModule' // 配置用户子模块 } ]; @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule] }) export class AppRoutingModule { }
我们给app.component.html新增两个button
<!--The content below is only a placeholder and can be replaced.--> <div style="text-align:center"> <h2> Welcome to {{ title }}! </h2> </div> <button routerLink="/user/list">user</button> //路由跳转 <button routerLink="/order/list">order</button> <router-outlet></router-outlet>
惰性加载模块有什么好处呢?
在大型项目中往往有许多个模块,而且大很大。如果一个模块1m,如果我们在浏览器输入地址打开这个应用,瞬间要加载100m 是非常慢的,而且我们并非要是用到着这100个模块。
将系统业务拆分为各个模块,划分好界限。按需加载,我点击了user 就加载user 模块,页面出现user 列表,对user进行操作。当我需要使用时才加载,极大的减少了页面初始加载的时间以及减少了资源的消耗。
共享模块顾名思义,就是共享于所有的模块中。首先得定义好这个模块的具体功能特性,比如指令、管道和组件等分别封装成一个个模块,哪些业务模块需要使用到其里面的功能便导入其模块中便可。 这极大的规范了系统的统一性和降低了以后的维护成本。
如果你引入了第三方UI,就不要把UI引入共享模块中导出,这样你的共享模块越来越庞大。别人UI框架设计的初衷就是按需加载。你把UI组件放到共享模块,加载那些无关的的UI组件,会浪费掉大量的性能。
For more programming-related knowledge, please visit: Programming Video! !
The above is the detailed content of Understand the concepts related to angular10 modules and get started quickly!. For more information, please follow other related articles on the PHP Chinese website!