我搜索了这个问题,但没有找到,并尝试了很多解决这个问题,但我是新的角2和创建的角度文档的帮助下的演示应用程序。 我的应用程序在一段时间之前已成功运行。但是,当我添加新的服务,然后我得到这个例外:例外:没有HeroService的提供者?
例外:没有提供HeroService!
我确定我在某处做错了,谁能告诉我我做错了什么地方?
文件夹结构:
app
app.component.ts
app.module.ts
hero.service.ts
hero.ts
hero-detail.component.ts
main.ts
mock-hero.ts
node_modules ...
index.html
package.json
styles.css
systemjs.config.js
tsconfig.json
app.component.ts-
//app.component.ts
import { Component, OnInit } from '@angular/core';
import { Hero } from './hero';
import { HeroService } from './hero.service';
@Component({
selector: 'my-app',
template: `
<h1>{{title}}</h1>
<h2>My Heroes</h2>
<ul class="heroes">
<li *ngFor="let hero of heroes"
[class.selected]="hero === selectedHero"
(click)="onSelect(hero)">
<span class="badge">{{hero.id}}</span> {{hero.name}}
</li>
</ul>
<my-hero-detail [hero]="selectedHero"></my-hero-detail>`,
})
export class AppComponent implements OnInit {
title = 'Tour of Heroes';
heroes: Hero[];
selectedHero: Hero;
constructor(private heroService: HeroService) { }
getHeroes(): void {
this.heroService.getHeroes().then(heroes => this.heroes = heroes);
}
ngOnInit(): void {
this.getHeroes();
}
onSelect(hero: Hero): void {
this.selectedHero = hero;
}
}
hero.service.ts-
// hero.service.ts
import { Injectable } from '@angular/core';
import { Hero } from './hero';
import { HEROES } from './mock-heroes';
@Injectable()
export class HeroService {
getHeroes(): Promise<Hero[]> {
return Promise.resolve(HEROES);
};
getHeroesSlowly(): Promise<Hero[]> {
return new Promise(resolve => {
// Simulate server latency with 2 second delay
setTimeout(() => resolve(this.getHeroes()), 2000);
});
}
}
hero.ts-
//hero.ts
export class Hero {
id: number;
name: string;
}
模拟heroes.ts-
//mock-heroes.ts
import { Hero } from './hero';
export const HEROES: Hero[] = [
{id: 11, name: 'Mr. Nice'},
{id: 12, name: 'Narco'},
{id: 13, name: 'Bombasto'},
{id: 14, name: 'Celeritas'},
{id: 15, name: 'Magneta'},
{id: 16, name: 'RubberMan'},
{id: 17, name: 'Dynama'},
{id: 18, name: 'Dr IQ'},
{id: 19, name: 'Magma'},
{id: 20, name: 'Tornado'}
];
app.module.ts-
//app.module.ts
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import {FormsModule} from '@angular/forms'
import { AppComponent } from './app.component';
import { MyComponent } from './my.component';
import { ShubhComponent } from './my.component';
import { HeroDetailComponent } from './hero-detail.component';
@NgModule({
imports: [ BrowserModule,FormsModule ],
declarations: [ AppComponent ,MyComponent,HeroDetailComponent,ShubhComponent],
bootstrap: [ AppComponent ]
})
export class AppModule { }
更好地了解我附上快照:
你必须使用提供者而不是注射剂 – MMK
你能分享app.module.ts吗? –
谢谢,但请你具体。我正在使用@Injectable() export class HeroService {0} {0} {0} getHeroes():Promise { return Promise.resolve(HEROES); }; –