Angular模块(NgModule)功能在Angular RC5中发布了!
Angular Modules (NgModules) have landed in Angular RC5!
Angular模块(也叫NgModule)是组织代码和引导应用的强力新途径。
要了解更多,参见"RC5和NgModule"正式发布。
要深入了解NgModule,参见Angular Module页。
新的@NgModule
装饰器让我们可以指定模块级的组件、指令和管道,而不需要在应用中的每个组件中都指定它们。
@NgModule
元数据为Angular编译器提供了上下文环境,以便我们可以让同一套代码分别运行在预编译AoT模式或即时编译JiT模式。
如何使用?
How do I use them?
如果你曾经写过Angular应用,那么它应该仍然能在RC5中工作。 我们付出了很多努力来确保RC4中的应用也能正常工作在RC5中。
- We create an implicit
NgModule
for you as part of thebootstrap()
command - 我们在
bootstrap()
命令中会为你创建一个隐式的NgModule
- We automatically hoist your components, pipes, and directives
- 我们会自动升级你的组件、管道和指令
虽然应用仍然能工作,但你最好还是升级下应用,以确保未来的升级和废弃的特性不会给你带来困扰。 要让这项工作更容易,你可以遵循如下五个步骤:
Update to RC5 - Your application should continue to work without modification, but it’s important that you are running the latest version of Angular.
升级到RC5 - 你的应用不用修改也仍然能正常工作,但重点是你要运行在最新版本的Angular中。
Create an NgModule - Create the root
NgModule
that you’ll use to bootstrap your application.创建NgModule - 创建一个根
NgModule
,你要用它来引导应用程序。Update your bootstrap - Bootstrap that module instead of your root component
升级你的引导代码 - 改成引导根模块,而不再是根组件
Update your 3rd party libraries - Take advantage of the latest from Forms, Material, Http, and more
升级你的第三方库 - 获得最新版表单、Material设计、Http等模块的优点
Cleanup - Clean up your code. The deprecated classes, methods and properties will be removed from Angular very soon.
清理 - 清理你的代码。那些被标记为废弃的类、方法和属性将很快从Angular中移除
想看看代码级变更? 那就来这个提交吧。
1. 升级到RC5
1. Update to RC5
如果使用npm,那么你可以手动修改package.json
文件并运行npm install
命令,或者直接运行下列命令:
npm install @angular/{core,common,compiler,platform-browser,platform-browser-dynamic} --save
更新你的可选库
npm install @angular/router
npm install @angular/forms
npm install @angular2-material/{core,button,card,...}@latest
如果你在使用Angular CLI,也要更新它
npm install angular-cli @angular/tsc-wrapped --save-dev
2. 创建NgModule
2. Create an NgModule
创建一个名叫app.module.ts
的新文件,把以前的根组件换成这样:
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app.component';
@NgModule({
declarations: [AppComponent],
imports: [BrowserModule],
bootstrap: [AppComponent],
})
export class AppModule {}
3. 升级你的引导代码
3. Update your bootstrap
升级main.ts
文件,改用即时(JiT)编译器来引导。
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { AppModule } from './app/app.module';
platformBrowserDynamic().bootstrapModule(AppModule);
4. 在NgModule中导入库模块
4. Import library modules in your NgModule
从你的AppComponent
的providers
中移除Angular和第三方库中的服务提供商,改为使用NgModule
中的imports
,就像这样:
imports: [
BrowserModule,
// Router
RouterModule.forRoot(config),
// Forms
FormsModule,
// Material Design
MdSlideToggleModule,
MdButtonModule,
MdToolbarModule,
MdCardModule,
MdInputModule,
],
5. 清理
5. Cleanup
对于RC5来说,你仍然可以在@Component
元数据的directives
和pipes
属性中指定组件、指令和管道。
实际上,我们会自动把它们加入到它们所属的NgModule中去。
这个选项只是为了向后兼容而临时设置的。 当Angular 2.0正式发布的时候,它将会被移除。
你可以先继续,但要尽早把这些组件、指令和管道移到模块的declarations
中。
我们准备在下一个RC中删除所有废弃的类、方法和属性。