Angular2 - Starter - NgModule
当你安装完成Ng2开发环境时,你可能从NgModule开始去写一个Ng2的app,一个Angular2的应用,一般通过一个NgModule来启动,而在NgModule中需要定义root component,申明sub component,sub modules,providers等.
1.导入基本模块
1 import { NgModule, ApplicationRef,Pipe } from '@angular/core';
2 import { BrowserModule } from '@angular/platform-browser';
3 import { FormsModule } from '@angular/forms';
4 import { HttpModule } from '@angular/http';
5 import { TailNumberPipeModule } from './components/extensions/pipes/tail-number-only/tail-number-length.module';
6 import { RouterModule, PreloadAllModules } from '@angular/router';
7 import { ROUTES } from './app.routes';
2.导入应用模块
// AppComponent is our top level component import { AppComponent } from './app.component'; import { APP_RESOLVER_PROVIDERS } from './app.resolver';
//应用级别的service import { AppState, InternalStateType } from './app.service';
//EnvSvc是一个公共的service,它提供当前应用环境的识别,并且返回当前环境的应用服务应访问的API Server等
import { EnvSvc } from './services/environment.service';
//主要子组件 import { HomeComponent } from './components/sections/home'; import { AboutComponent } from './components/sections/about';
import { LogOnComponent } from './components/sections/logon'; import { FriendsComponent } from './components/sections/friends';
//people-finder 是用来搜索用户的一个控件 import { PeopleFinderComponent } from './components/controls/people-finder';
//AgeGroupDevider 是一个自定义指令(Directive),根据输入的生日,划分该用户的年龄段,并改变用户信息容器的展现形式. import { AgeGroupDevideDiretive } from './components/extensions/directives/age-group-devider';
//TailNumberPipeMudule是一个自定义模块,它提供一个通道(Pipe),可以理解为适配器,通过输入的电话号码,返回隐藏指定数量的尾号. import { TailNumberPipeModule } from './components/extensions/pipes/tail-number-only/tail-number-length.module';
3.为了区分开Custom Directive,Sub Component,Custom Module等的引入,我们将这些模块进行分类
const APP_PROVIDERS = [ ...APP_RESOLVER_PROVIDERS, AppState,
//这里申明的提供商可以注入到其他service,component,directive中
//class UserSvc{
// constructor(public envSvc:EnvSvc){
// }
//}
EnvSvc ]; const APP_EXTENSIONS_DECLARATIONS = [ AgeGroupDevideDiretive ]; const APP_EXTENSIONS_PIPEMODULES = [ TailNumberPipeModule ]; const APP_CONTROLS_DECLARATIONS = [ PeopleFinderComponent ]; const APP_MAIN_COMPONENTS = [ AppComponent, LogOnComponent, FriendsComponent, ChatsComponent, AboutComponent, HomeComponent ];
4.导出一个类,并未该类增加NgModule修饰
@NgModule({
//应用根组件 bootstrap: [ AppComponent ],
//申明主要组件,控件,自定义指令,扩展模块 declarations: [ ...APP_MAIN_COMPONENTS, ...APP_CONTROLS_DECLARATIONS, ...APP_PUBLIC_DIRECTIVES, ...APP_EXTENSIONS_DECLARATIONS ],
//导入基本模块和自定义模块
//导入的应是@NgModule修饰的类 imports: [ // import modules BrowserModule, FormsModule, HttpModule, ...[APP_EXTENSIONS_PIPEMODULES], RouterModule.forRoot(ROUTES, { useHash: true, preloadingStrategy: PreloadAllModules }) ],
//申明提供商,主要包括一些service providers: [ ENV_PROVIDERS, ...APP_PROVIDERS ] }) export class AppModule {
//在应用主模块的构造函数中注入AppState这个service constructor(public appRef: ApplicationRef, public appState: AppState) {}
}