Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

declare properties in constructor angular 2

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 the top of the class.

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

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

or like this

private router: Router
private heroService: HeroService

constructor( ) {}
like image 462
Roberto Fernandez Diaz Avatar asked Jul 05 '16 20:07

Roberto Fernandez Diaz


1 Answers

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.

like image 163
malifa Avatar answered Oct 13 '22 22:10

malifa