Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 665
Daniel Stradowski Avatar asked Oct 30 '22 21:10

Daniel Stradowski


1 Answers

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');
  }
}
like image 166
Mikki Kobvel Avatar answered Nov 15 '22 07:11

Mikki Kobvel