Anthony Davis Anthony Davis - 1 month ago 16
TypeScript Question

Angular Providers

Following the angular 2 tutorial @ https://angular.io/docs/ts/latest/tutorial/toh-pt4.html

In the

@Component({
})


I inserted "
providers: [HeroService]
" which contains the
getHeroes()
method.

Created a constructor:

constructor(private heroService: HeroService) {}


Now the part I don't understand is how I am able to use

this.heroService.getHeroes()


The only propertes defined in this class are:

title = 'Tour of Heroes';
heroes: Hero[];
selectedHero: Hero;


Does the providers in the
@Component
decorator automatically create a property to access it through
this.
?


The App is working, just don't know how we magically were able to access heroService through
this.

Answer

The private (could also be public) in

constructor(private heroService: HeroService) {}

also creates a property heroService and assigns the value passed to the constructor. That's a TypeScript feature and is not Angular2 or DI dependent.