我找不到区别:
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'); } }