简体   繁体   English

TypeScript 中 Angular 2 的最佳实践

[英]Best practice for Angular 2 in TypeScript

I'm trying to rewrite my app in Angular 2 typescript and would like to use best practices.我正在尝试用 Angular 2 打字稿重写我的应用程序,并希望使用最佳实践。 I've found the following guide but it doesn't answer my very basic questions.我找到了以下指南,但它没有回答我非常基本的问题。 Here is two questions:这里有两个问题:

  1. In Components, is it ok to declare a local variable inside a function or should I declare it as private, right above the constructor?在组件中,可以在函数内部声明局部变量还是应该将其声明为私有变量,就在构造函数的正上方?
  2. How should I call variables inside nested functions?我应该如何在嵌套函数中调用变量? For example:例如:

     replicator(){// return observable} myFunction(){// Nested function to be called} ngOnInit() { this.replicator().subscribe(function (data) { // Call function here } }

    Should I call my function by doing: let self = this before this.replicator() and then call self.myFunction() ?我应该通过以下方式调用我的函数: let self = this before this.replicator()然后调用self.myFunction()吗? Or is there a better way to do this?或者有没有更好的方法来做到这一点?

PS If you have a good best practice guide, please post it as a comment! PS如果您有好的最佳实践指南,请将其作为评论发布!

How should I call variables inside nested functions我应该如何在嵌套函数中调用变量

Use an arrow function ( 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是否可以在函数内部声明局部变量,或者我应该将其声明为私有变量,就在构造函数的正上方

Both are fine.两者都很好。 Local if its only local to the function or private if other functions might need it 🌹本地如果它只是函数的本地或private如果其他函数可能需要它🌹

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM