Daniel Stradowski Daniel Stradowski - 3 months ago 10
TypeScript Question

Do I need constructor body in Angular2?

I couldn't find a difference between:

constructor (private router: Router) { }


and

router: Router;

constructor (private _router: Router) {
this.router = _router
}


Variable
router
is available in the whole class and it contains the same data. So what's the difference between first and the second syntax?

Answer

Basically this:

constructor (private router: Router) { }

is short form of this:

private router: Router;    

constructor (_router: Router) {
    this.router = _router
}  

Personally I use first format in all projects because it makes files shorter, and it is easier to read.

If your question about block inside of constructor, answer is - no. If you are using short form like I showed before, there no need to put anything in constructor. All needed init stuff you can put in ngOnInit function.

Short example:

@Component({
  selector: 'my-cmp',
  template: `<p>my-component</p>`
})
class MyComponent implements OnInit {
constructor(
    private router: Router,
    private myService: MyService
) { }

  ngOnInit() {
    console.log('ngOnInit');
  }
}