After searching extensively for an answer to this question without success, I am reaching out for help. As a newcomer to Angular 2, I have been creating a demo app with reference to the Angular docs. Everything was running smoothly until I added a new service and encountered the following exception:
EXCEPTION: No provider for HeroService!
I am certain that I must be making a mistake somewhere. Can anyone point me in the right direction?
Folder Structure:
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;
}
mock-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 { }
For better clarity, I have attached a snapshot here.