2017-02-22 120 views
1

我有我的主要模塊是這樣,我在那裏導入基本庫:角2模塊導入

import { BrowserModule } from '@angular/platform-browser'; 
import { NgModule } from '@angular/core'; 
import { MaterialModule } from '@angular/material'; 
import { FormsModule } from '@angular/forms'; 
import { HttpModule } from '@angular/http'; 

import { MapModule } from './map/map.module'; 

import { AppComponent } from './app.component'; 

@NgModule({ 
    declarations: [ 
    AppComponent 
    ], 
    imports: [ 
    BrowserModule, 
    FormsModule, 
    HttpModule, 
    MapModule, 
    MaterialModule.forRoot() 
    ], 
    providers: [], 
    bootstrap: [AppComponent] 
}) 
export class AppModule { } 

我的問題是,當我創建應用程序,即地圖模塊,我需要重新導入所有內一個新的模塊那些模塊庫。我的印象是,如果我在模塊上導入庫,它將在子模塊下工作。

但在我的地圖模塊中,我收到類似的錯誤。

Can't bind to 'ngClass' since it isn't a known property of 'div'. 

我目前MapModule看起來像

import { NgModule } from '@angular/core'; 

import { MapComponent } from './map.component'; 
import { MapMenuComponent } from './map-menu/map-menu.component'; 
import { MapControlsComponent } from './map-controls/map-controls.component'; 
import { MapService } from './map.service'; 


@NgModule({ 
    imports: [], 
    exports: [], 
    declarations: [MapMenuComponent, MapControlsComponent, MapComponent], 
    providers: [MapService], 
}) 
export class MapModule { } 

我需要重新導入MaterialModule,表單等進入模塊再次爲這個模塊中的組件協同工作?

回答

3

您只需要用聲明重新導入模塊,即定義新組件,指令和管道的模塊。註冊提供者的模塊不需要導入。

在這份名單中:

imports: [ 
    BrowserModule, 
    FormsModule, 
    HttpModule, 
    MapModule, 
    MaterialModule.forRoot() 
    ], 

FormsModule模塊需要進口,由HttpModule不需要。 BrowserModule轉口CommonModule,所以在其他模塊中,您可能需要導入CommonModule而不是BrowserModule以獲得像NgClass這樣的內置指令。通過導入CommonModule,您不會有此錯誤:

Can't bind to 'ngClass' since it isn't a known property of 'div'.

+2

阿疑難雜症,我想捆紮機喜歡的WebPack足夠聰明,只能將這些模塊(如材質和表單)僅放入捆綁包中,而不是多次。 – StevieB

+0

謝謝大家解釋清楚的答案,我發現這種情況缺乏他們的文檔。 – StevieB

+0

@StevieB,當然,捆綁軟件或其他類似systemjs的加載程序只會導入一次模塊。是的,那部分在文檔中是不清楚的。更糟糕的是,它們不包含npm包中的源代碼,所以你必須去github去檢查哪些模塊有聲明。 –

0

您可以使用SharedModule。所有模塊的使用在多個模塊

sharedModule例如

import { NgModule } from '@angular/core'; 
import { anyService} from './any.service'; 

@NgModule({ 
    providers: [anyService] 
}) 
export class SharedModule {} 

現在你可以在任何模塊導入此共享的模塊中,要使用這個模塊