I am a java programer that just has landed in angular 2. When doing the official tutorial, I was surprised to see that they declare this properties in the constructor instead of
While this:
private router: Router
private heroService: HeroService
just declares two private properties of your class of type Router
and HeroService
,
this:
constructor(private router: Router, private heroService: HeroService) {}
injects an instance of Router
(and HeroService
), additionally creates two private properties and assigns the injected instances of your services to these in one statement.
For a better understanding, this does the same:
private _router: Router;
private _heroService: HeroService;
constructor(router: Router, heroService: HeroService) {
this._router = router;
this._heroService = heroService;
}
With the "first approach" you don't have an instance of these services.
Sidenote: providers: [Router, HeroService]
which you might have somewhere in one of your Component Anntations
just give your components the possibility to inject them, but doesn't actually do it, that's why you probably end up injecting them always via your constructor
method.