AngularJS参考手册
Angular 模块
JS模块 vs NgModule
前提条件
对 JavaScript/ECMAScript 模块 有基本的了解。
JavaScript 和 Angular 都使用模块来组织代码,虽然它们的组织形式不同,但 Angular 的应用会同时依赖两者。
JavaScript 模块
在 JavaScript 中,模块是内含 JavaScript 代码的独立文件。要让其中的东西可用,你要写一个导出语句,通常会放在相应的代码之后,类似这样:
content_copyexport class AppComponent { ... }
然后,当你在其它文件中需要这个文件的代码时,要像这样导入它:
content_copyimport { AppComponent } from './app.component';
JavaScript 模块让你能为代码加上命名空间,防止因为全局变量而引起意外。
NgModules
NgModule 是一些带有 @
NgModule
装饰器的类。@
NgModule
装饰器的 imports
数组会告诉 Angular 哪些其它的 NgModule 是当前模块所需的。imports
数组中的这些模块与 JavaScript 模块不同,它们都是 NgModule 而不是常规的 JavaScript 模块。 带有 @
NgModule
装饰器的类通常会习惯性地放在单独的文件中,但单独的文件并不像 JavaScript 模块那样作为必要条件,而是因为它带有 @
NgModule
装饰器及其元数据。
Angular CLI 生成的 AppModule
实际演示了这两种模块:
content_copy/* These are JavaScript import statements. Angular doesn’t know anything about these. */import { BrowserModule } from '@angular/platform-browser';import { NgModule } from '@angular/core'; import { AppComponent } from './app.component'; /* The @NgModule decorator lets Angular know that this is an NgModule. */@NgModule({ declarations: [ AppComponent ], imports: [ /* These are NgModule imports. */ BrowserModule ], providers: [], bootstrap: [AppComponent]})export class AppModule { }
NgModule 类与 JavaScript 模块有下列关键性的不同:
- Angular 模块只绑定了可声明的类,这些可声明的类只是供Angular 编译器用的。
- 与 JavaScript 类把它所有的成员类都放在一个巨型文件中不同,你要把该模块的类列在它的
@
NgModule.declarations
列表中。 - Angular 模块只能导出可声明的类。这可能是它自己拥有的也可能是从其它模块中导入的。它不会声明或导出任何其它类型的类。
- 与 JavaScript 模块不同,NgModule 可以通过把服务提供商加到
@
NgModule.providers
列表中,来用服务扩展整个应用。
关于 NgModule 的更多知识
要了解关于 NgModule 的更多知识,参见
- 引导启动。
- 常用模块。
- 服务提供商。