Angular 2模块导入

时间:2017-02-22 12:08:27

标签: javascript angular angular2-modules

我有这样的主模块,我导入基本的库:

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'.

My Current 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,Forms等重新导入模块,以使该模块中的组件正常工作?

2 个答案:

答案 0 :(得分:3)

您只需要使用声明重新导入模块,即定义新组件,指令和管道的模块。注册提供商的模块不需要导入。

在此列表中:

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

FormsModule模块需要导入,HttpModule不需要。 BrowserModule重新导出CommonModule,因此在其他模块中,您可能希望导入CommonModule,而不是BrowserModule以获取内置指令,例如NgClass。导入CommonModule您将不会出现此错误:

  

无法绑定到' ngClass'因为它不是' div'

的已知属性

答案 1 :(得分:0)

您可以使用SharedModule。所有模块都在多个模块中使用

sharedModule示例

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

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

现在,您可以在要使用此模块的任何模块中导入此共享模块