1

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.

Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
Anthony Davis
  • 139
  • 2
  • 11

1 Answers1

1

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.

Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
  • Interesting, so if I leave it blank, it defaults to public, but does not create a property, but the fact that you declare it as private or public will tell the class to create the property. Good to know. I can't wrap my head around _why_ this syntax should have anything to do with creating a property. Is it because by defining it as private or public, means that you are implying it will be reused? Sorry if this question doesn't make sense, I am fairly novice. But either way, thank you for the answer. Very good to know ;) – Anthony Davis Nov 08 '16 at 21:41
  • 1
    It's very common to assign constructor parameters to properties, therefore they created this syntactic shugar. If you omit `private` and `public` no property is created and the `heroService` exists only within the constructor. – Günter Zöchbauer Nov 08 '16 at 21:44