首页 文章

angular2,英雄之旅,ngmodule进口

提问于
浏览
1

我正在尝试使用Ngmodule和导入,所以我移动了这一行:(来自heroes.component.ts文件)从'./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 回答

  • 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

    在NgModule中进行'进口'的原因不是用于导入组件,而是用于导入另一个模块(另一个NgModules的文件,由另一个组件分组) .

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

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

相关问题