简体   繁体   English

Angular 2提供程序无法在组件中访问

[英]Angular 2 provider is not accessible in components

I am new on angular 2. I was following the legacy quick-start application, Tour of Heroes. 我是angular 2的新手。我关注的是旧版快速入门应用程序“英雄之旅”。

I created services as mentioned in the application. 我创建了应用程序中提到的服务。

I have a service HeroService. 我有服务HeroService。 Which is used to pull all the heroes data. 用于提取所有英雄数据。

I have included the HeroService at the app.module file as provider to be able to access it through out the application for all application. 我已经将HeroService作为提供程序包含在app.module文件中,以便能够通过应用程序为所有应用程序访问它。

My app.module.ts 我的app.module.ts

import { NgModule }      from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { RouterModule } from '@angular/router';

import { AppComponent }  from './app.component';
import { HeroDetailComponent }  from './hero-detail.component';
import { HeroesComponent }  from './heroes.component';
import { HeroService }  from './hero.service';

@NgModule({
  imports: [
    BrowserModule,
    FormsModule,
    RouterModule.forRoot([
      {
        path: 'heroes',
        component: HeroesComponent
      }
    ])
  ],
  declarations: [ AppComponent, HeroesComponent, HeroDetailComponent ],
  providers: [ HeroService ],
  bootstrap: [ AppComponent ]
})
export class AppModule { }

And my Component File where I want to Access the HeroService to get data is: 我要访问HeroService来获取数据的组件文件是:

export class HeroesComponent implements OnInit {
    constructor(private heroService: HeroService) { }
}

The problem is I am getting an error like this, when i build the project : 问题是当我构建项目时出现这样的错误:

Cannot find name 'HeroService'. 找不到名称“ HeroService”。

I have followed all the steps correctly. 我正确地遵循了所有步骤。 If I import the HeroService in my HeroesComponent, it seems to work. 如果我在HeroesComponent中导入HeroService,它似乎可以工作。 But fails when not imported. 但是,如果未导入,则会失败。 Am I missing some step. 我错过了一些步骤吗? As far as I understood declaring the provider on app.module will register it to use throughout the application/components without need of importing it each time. 据我了解,在app.module上声明提供程序会将其注册为可在整个应用程序/组件中使用,而无需每次都导入它。

Please correct me If I am wrong somewhere. 如果我在某处错了,请纠正我。

您还需要在组件内部导入

import { HeroService }  from './hero.service';

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

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