简体   繁体   English

angular2,英雄之旅,ngmodule进口

[英]angular2 , Tour of Heroes , ngmodule imports

I'm trying practice use Ngmodule and imports, so I moved this line: (from heroes.component.ts file) import { Hero } from './hero'; 我正在尝试使用Ngmodule和import进行练习,所以我移动了这一行:(来自heroes.component.ts文件)从'./hero'中导入{Hero};

to app.module.ts file: 到app.module.ts文件:

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

but i get this error: 但我得到这个错误:

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

It's possible to let in the components just the basic import: import { Component, OnInit } from '@angular/core'; 可以只将基本导入导入组件:从'@ angular / core'导入{Component,OnInit}; and move all the rest imports to NgModule? 并将所有其余的导入移动到NgModule? or have I restrictions? 还是我有限制?

Yes, there are restrictions to what should be included inside an NgModule. 是的,对NgModule中应包含的内容有一些限制。 Esentially a module groups together a set of functionality, you can only add components, directives, services and other modules to an NgModule, your hero import should be inside a component, not a module. 基本上,一个模块将一组功能组合在一起,您只能将组件,指令,服务和其他模块添加到NgModule中,您的英雄导入应该在组件内部,而不是模块内部。

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

So your files would be 所以你的文件将是

//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;
}

And: 和:

//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 { }

The reason that propery 'imports' in NgModule is not for import components but to import another modules (files where another NgModules , grouped by another components ). 在NgModule中适当地“导入”的原因不是为了导入组件,而是为了导入另一个模块(其中另一个NgModules的文件,由另一个组件分组)。

Components can be moved to Ngmodule in 'imports:' property: the import line: import { } from '..'; 组件可以在'imports:'属性中移动到Ngmodule:导入行:从'..'中的import {}; and 'directives' line 和“指令”行

Service can be moved to NgModule in 'providers:' property but the difference it's that service must to keep in the component the: import { } from '..'; 可以在“ providers:”属性中将服务移至NgModule,但区别在于服务必须将组件保留在组件中:import {} from'..';

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM