加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

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

发布时间:2020-12-17 17:07:38 所属栏目:安全 来源:网络整理
导读:我找不到区别: constructor (private router: Router) { } 和 router: Router; constructor (private _router: Router) { this.router = _router} 变量路由器在整个类中可用,它包含相同的数据.那么第一种语法和第二种语法之间的区别是什么? 解决方法 基本
我找不到区别:

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');
  }
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读