Daniel Stradowski Daniel Stradowski - 1 year ago 139
TypeScript Question

Do I need constructor body in Angular2?

I couldn't find a difference between:

constructor (private router: Router) { }


router: Router;

constructor (private _router: Router) {
this.router = _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 Source

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:

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

  ngOnInit() {
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download