angular2,英雄之旅,ngmodule进口

时间:2016-08-22 03:58:31

标签: angular

我尝试使用Ngmodule和导入,所以我移动了这一行: (来自heroes.component.ts文件)          从' ./ hero'中导入{Hero};

到app.module.ts文件:

    import { Hero } from './hero';
    @NgModule({
        imports: [
         BrowserModule,
         FormsModule,
         routing,
         Hero
        ],

但是我收到了这个错误:

[0] app/heroes.component.ts(20,11): error TS2304: Cannot find name 'Hero'

可以让组件只进行基本导入: 从' @ angular / core'中导入{Component,OnInit}; 并将所有其余的导入移动到NgModule?或者我有限制吗?

2 个答案:

答案 0 :(得分:1)

是的,对NgModule中应该包含的内容有限制。实际上,一个模块将一组功能组合在一起,你只能向NgModule添加组件,指令,服务和其他模块,你的英雄导入应该在一个组件内,而不是一个模块。

import { Hero } from './hero';
//This import should stay inside app.component.ts

所以你的文件将是

//app.component.ts
import { Component } from '@angular/core';

import { Hero } from './hero';

@component({
  selector: 'my-app',
  template: `<p>A template goes in here</p>`
})
export class AppComponent {
  public hero: Hero;
}

并且:

//app.module.ts
import { NgModule }      from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';

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

@NgModule({
  imports: [ BrowserModule ], //other modules you require
  declarations: [ AppComponent ], //declares components and directives
  bootstrap: [ AppComponent ] //your root component
})
export class AppModule { }

答案 1 :(得分:1)

NgModule中的'导入'的原因不是导入组件,而是导入另一个模块(其他NgModule的文件,由其他组件分组)。

可以在'imports:'属性中将组件移动到Ngmodule: 导入行:import {} from'..';和'指令'行

可以将服务移动到'providers:'属性中的NgModule 但不同之处在于服务必须保留在组件中:import {} from'..';

相关问题