【问题标题】:What is the meaning of this error "Declaration of instance field not allowed after declaration of instance method."这个错误“声明实例方法后不允许声明实例字段”是什么意思。
【发布时间】:2017-08-04 20:15:47
【问题描述】:

在我的 Angular2 项目中,我收到此错误:

“在声明实例方法之后不允许声明实例字段。相反,这应该出现在类/接口的开头。(成员排序)”

我想了解如何解决此问题以及为什么会出现此问题。

错误与下一段代码中的私有函数有关:

export class HomeComponent implements OnInit {
public error: string;
public shirts = [];


constructor(public rest: RestService,
            public scService: ShoppingCartService,
            public snackBar: MdSnackBar) {
}


ngOnInit() {
    this.rest.getAll().subscribe((r: any) => {
        this.shirts = r;
    }, error => {
        this.error = 'Opps there\'s some error';
    });

}

addToCart(shirt: any) {
    this.scService.add(shirt);
    this.showSnackMessage('Added to Chart List');
}

showSnackMessage(message: string) {
    this.snackBar.open(message, null, {
        duration: 1000
    });
}
//Here the error is showed
private sizeScore = {
    'string': -1,
    s: 0,
    m: 1,
    l: 2,
    'x-large': 3,
};

sortData(sort: Sort) {
    const data = this.shirts.slice();
    if (!sort.active || sort.direction === '') {
        this.shirts = data;
        return;
    }

    this.shirts = data.sort((a, b) => {
        let isAsc = sort.direction === 'asc';
        switch (sort.active) {
            case 'colour':
                return compare(a.colour, b.colour, isAsc);
            case 'size':
                return compare(this.sizeScore[a.size], this.sizeScore[b.size], isAsc);
            default:
                return 0;
        }
    });
}
}

【问题讨论】:

标签: javascript angular typescript


【解决方案1】:

我猜您的项目设置了某种类型的 linting,可以在构建时检查样式问题。

要修复它,你只需要按照它说的去做。将代码移至任何方法调用之前。

export class HomeComponent implements OnInit {
public error: string;
public shirts = [];
private sizeScore = {
    'string': -1,
    s: 0,
    m: 1,
    l: 2,
    'x-large': 3,
};
// ...

【讨论】:

  • 但这对代码运行有影响吗?还是执行最佳实践有问题?
  • 不,对代码的运行没有影响。 linter 正在执行代码样式最佳实践。
  • 如果有private成员比如private age: number;
  • 如果你想确保你的 linting 无错误通过,它们只需要在任何函数之上。
【解决方案2】:

这实际上不是编译/运行时错误,而是代码 linting 问题。

将类的所有属性放在方法之上是一个很好的做法,因此如果您只是将private sizeScore 移到顶部,它将停止显示。

有关此规则的更多信息here

【讨论】:

    【解决方案3】:

    根据TSLint docs,我认为您只需将字段声明移到这些方法的声明上方即可。

    【讨论】:

      【解决方案4】:

      public-before-privatestatic-before-instance 现已弃用

      【讨论】:

        猜你喜欢
        • 2014-09-20
        • 2022-12-05
        • 2013-07-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-07-20
        相关资源
        最近更新 更多