【问题标题】:Angular 2 provider is not accessible in componentsAngular 2 提供程序在组件中不可访问
【发布时间】:2017-06-20 11:57:13
【问题描述】:

我是 Angular 2 的新手。我关注的是旧版快速启动应用程序《英雄之旅》。

我创建了应用程序中提到的服务。

我有一个服务 HeroService。用于拉取所有英雄数据。

我在 app.module 文件中包含了 HeroService 作为提供者,以便能够通过应用程序为所有应用程序访问它。

我的 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 { }

我想要访问 HeroService 以获取数据的组件文件是:

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

问题是我在构建项目时遇到这样的错误:

找不到名称“HeroService”。

我已正确执行所有步骤。如果我在我的 HeroesComponent 中导入 HeroService,它似乎可以工作。但未导入时失败。 我是否错过了一些步骤。据我了解,在 app.module 上声明提供程序将注册它以在整个应用程序/组件中使用,而无需每次都导入它。

如果我在某处错了,请纠正我。

【问题讨论】:

  • 你在组件文件中导入HeroService了吗?
  • 您是否从hero.service.ts 文件中导出了HeroService 类?
  • 不,这不是我的查询,如果我需要再次导入它,因为我已经在 app.module 中将其添加为提供程序。以为我们可以不导入它。现在我认为将它作为提供程序添加到 app.module 中没有意义,因为我们每次都必须导入它。

标签: javascript angular angular2-services


【解决方案1】:

您还需要在组件内部导入

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

【讨论】:

  • 所以即使我们在app.module providers中添加了也需要导入?
  • 我认为没有必要,因为我们已经在 app.module 中将其定义为提供程序。感谢您的及时答复。我之前导入了,但是我们是否可以避免导入感到困惑。现在我认为将它作为提供程序包含在 app.module 中没有意义,因为我们每次都必须导入它。只是我们可以避免组件装饰器中的提供者键。或者我看不到背后的大局。
猜你喜欢
  • 2018-06-18
  • 2019-03-02
  • 2018-05-27
  • 2016-11-14
  • 2017-02-25
  • 1970-01-01
  • 2013-03-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多