typescript - TypeScript 中 Angular 2 的最佳实践

标签 typescript angular

我正在尝试使用 Angular 2 typescript 重写我的应用程序,并希望使用最佳实践。我发现以下 guide但它没有回答我非常基本的问题。这里有两个问题:

  1. 在组件中,可以在函数内声明局部变量吗?还是应该将其声明为私有(private)变量,就在构造函数之上?
  2. 我应该如何在嵌套函数中调用变量?例如:

    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/

相关文章:

带有注释参数属性的 Typescript jsdoc

angularjs - 如何延长 te 浏览器超时以避免 504 http 错误?

javascript - 如何在 Vue.Js 的 v-for 循环中转义 'Duplicate keys detected'?

javascript - HTML5 : Attributes are not recognized after being added with JS/Jquery

reactjs - 使用 TypeScript 设置 React 组件的状态类型

javascript - 你如何使用 jasmine + TypeScript 测试一个用常量调用的函数

javascript - MomentJS 检查 isBefore 没有日期

javascript - 错误 TS2304 : Cannot find name 'trim' in Angular 5

javascript - 使用 angular-cli 在仅生产环境中包含许可证文件

angular - 获取外部 JS 库以用于 Angular 2