Angular2學習筆記——NgModule

來源:互聯網
上載者:User

標籤:

  在Angular2中一個Module指的是使用@NgModule修飾的class。@NgModule利用一個中繼資料對象來告訴Angular如何去編譯和運行代碼。一個模組內部可以包含組件、指令、管道,並且可以將它們的存取權限聲明為公有,以使外部模組的組件可以訪問和使用到它們。

  模組是用來組織應用的,通過模組機制外部類庫可以很方便的擴充應用,Rc5之後,Angular2將許多常用功能都分配到一個個的模組中,如:FormModule、HttpModule、RouterModule。

  NgModule的主要屬性如下:

  • declarations:模組內部Components/Directives/Pipes的列表,聲明一下這個模組內部成員
  • providers:指定應用程式的根層級需要使用的service。(Angular2中沒有模組層級別的service,所有在NgModule中聲明的Provider都是註冊在根層級的Dependency Injector中)
  • imports:匯入其他module,其它module暴露的出的Components、Directives、Pipes等可以在本module的組件中被使用。比如匯入CommonModule後就可以使用NgIf、NgFor等指令。
  • exports:用來控制將哪些內部成員暴露給外部使用。匯入一個module並不意味著會自動匯入這個module內部匯入的module所暴露出的公用成員。除非匯入的這個module把它內部匯入的module寫到exports中。
  • bootstrap:通常是app啟動的根組件,一般只有一個component。bootstrap中的組件會自動被放入到entryComponents中。
  • entryCompoenents: 不會再模板中被引用到的組件。這個屬性一般情況下只有ng自己使用,一般是bootstrap組件或者路由群組件,ng會自動把bootstrap、路由群組件放入其中。 除非不通過路由動態將component加入到dom中,否則不會用到這個屬性。

  每個Angular2的應用都至少有一個模組即跟模組。

import {NgModule} from ‘@angular/core‘;import {BrowserModule} from ‘@angular/platform-borwser‘;import {AppComponent} from ‘./AppComponent‘;@NgModule({    declarations: [AppComponent],    imports: [BrowserModule],    bootstrap: [AppComponent]})export class AppModule{}

 

  隨著程式的壯大,單一的根模組已不能清晰的劃分職責,這時候便可以引入Feature Module。Feature Module與根模組的建立方式一樣,所有的模組共用一個運行期上下文和依賴注入器。

  功能模組與根模組的職責區別主要有以下兩點:

  • 根模組的目的在於啟動app,功能模組的目的在於擴充app
  • 功能模組可以根據需要暴露或隱藏具體的實現

 

  Angular2提供的另一個與模組有關的技術就是消極式載入了。預設情況下Angular2將所有的代碼打包成一個檔案,目的是為了提高應用的流暢性,但是如果是運行在mobile中的app,載入一個大檔案可能會過慢,所以rc5提供了一種消極式載入方式。

template: `  <app-title [subtitle]="subtitle"></app-title>  <nav>    <a routerLink="contact" routerLinkActive="active">Contact</a>    <a routerLink="crisis"  routerLinkActive="active">Crisis Center</a>    <a routerLink="heroes"  routerLinkActive="active">Heroes</a>  </nav>  <router-outlet></router-outlet>`

 

import { ModuleWithProviders }  from ‘@angular/core‘;import { Routes, RouterModule } from ‘@angular/router‘;export const routes: Routes = [  { path: ‘‘, redirectTo: ‘contact‘, pathMatch: ‘full‘},  { path: ‘crisis‘, loadChildren: ‘app/crisis/crisis.module#CrisisModule‘ },  { path: ‘heroes‘, loadChildren: ‘app/hero/hero.module#HeroModule‘ }];export const routing: ModuleWithProviders = RouterModule.forRoot(routes);

  其中,path指明路徑,loadChildren指明使用消極式載入,‘app/crisis/crisis.module#CrisisModule‘指明了模組的路徑,和模組的名稱。

  

Angular2學習筆記——NgModule

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.