我正在尝试使用 Angular 2 typescript 重写我的应用程序,并希望使用最佳实践。我发现以下 guide但它没有回答我非常基本的问题。这里有两个问题:
- 在组件中,可以在函数内声明局部变量吗?还是应该将其声明为私有(private)变量,就在构造函数之上?
我应该如何在嵌套函数中调用变量?例如:
replicator(){// return observable} myFunction(){// Nested function to be called} ngOnInit() { this.replicator().subscribe(function (data) { // Call function here } }
我应该通过以下方式调用我的函数:在
this.replicator()
之前let self = this
然后调用self.myFunction()
?或者有更好的方法吗?
PS 如果您有好的最佳实践指南,请发表评论!
最佳答案
How should I call variables inside nested functions
使用箭头函数 ( more )。
ngOnInit() {
this.replicator().subscribe((data) => {
// Call function here
this.somefunction
}
}
is it ok to declare a local variable inside a function or should I declare it as private, right above the constructor
两者都很好。 Local 如果它只是函数的本地或者 private
如果其他函数可能需要它 🌹
关于typescript - TypeScript 中 Angular 2 的最佳实践,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37452801/