我是否需要Angular2中的构造函数体?

前端之家收集整理的这篇文章主要介绍了我是否需要Angular2中的构造函数体?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我找不到区别:

constructor (private router: Router) { }

router: Router;    

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

变量路由器在整个类中可用,它包含相同的数据.那么第一种语法和第二种语法之间的区别是什么?

解决方法

基本上这个:

constructor (private router: Router) { }

是这种简短形式:

private router: Router;    

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

我个人在所有项目中使用第一种格式,因为它使文件更短,更容易阅读.

如果你的问题是关于构造函数内部的阻塞,那么答案是 – 否.如果您使用的是我之前展示的简短形式,则无需在构造函数中放置任何内容.您可以放入ngOnInit函数中所需的所有初始化内容.

简短的例子:

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

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

猜你在找的Angularjs相关文章