Roberto Fernandez Roberto Fernandez - 1 year ago 101
AngularJS Question

declare properties in constructor angular 2

I am a java programer that just has landed in angular 2. I was doing the official tutorial of the web page and I was surprised when I see that they declare this properties in the constructor instead of the top of the class.

I know that Java and Js are very different , but there is any technical reason between doing like this

constructor(private router: Router ,private heroService: HeroService) {}

or like this

private router: Router
private heroService: HeroService

constructor( ) {}

Thanks for the help , Roberto .

Answer Source

While this:

private router: Router
private heroService: HeroService

just declares two private properties of your class of type Router and HeroService,


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.