I've been going through the "Heroes" tutorial on official Angular 2 page and when I came to routing, a couple of things didn't make sense. It's about providers.
The part in question is represented as follows. My main component looks like this:
/* app.components */
import {Component} from 'angular2/core';
import {HeroesComponent} from './heroes.component';
import {HeroService} from './hero.service';
@Component({
selector: 'my-app',
template: `
<h1>{{title}}</h1>
<my-heroes></my-heroes>
`
directives: [HeroesComponent],
providers: [HeroService]
})
export class AppComponent {
title = 'Tour of Heroes';
constructor(private _heroService: HeroService) {}
}
and the heroes components looks like this:
/* heroes.component */
import {Component} from 'angular2/core';
import {Hero} from './hero';
import {HeroDetailComponent} from './hero-detail.component';
import {HeroService} from './hero.service';
import {OnInit} from 'angular2/core';
@Component({
selector: 'my-heroes',
directives: [HeroDetailComponent],
template: `
<h2>My Heroes</h2>
<ul class="heroes">
<li *ngFor="#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 HeroesComponent implements OnInit {
heroes: Hero[];
selectedHero: Hero;
ngOnInit() {
this.getHeroes();
}
constructor(private _heroService: HeroService) { }
getHeroes() {
this._heroService.getHeroes().then(heroes => this.heroes = heroes);
}
onSelect(hero: Hero) {
this.selectedHero = hero;
}
}
OK, so my question: in order for this to work, I need to import import {HeroService} from './hero.service';
in both files. However, providers: [HeroService]
is only a part of the @Component
of app.components
. I needn't write this piece of code in heroes.component
. How does the heroes.component
know which provider to pick? Is it inherited from app.components
? And if so, why did I have to write this in both files: import {HeroService} from './hero.service';
? Why not just in app.components
? Both classes also have the same constructor
. I don't know what's going on here, so thanks in advance for any explanation.