在我的 Angular2 项目中,我收到此错误:
“在声明实例方法之后不允许声明实例字段。相反,这应该出现在类/接口(interface)的开头。(成员排序)”
我想了解如何解决这个问题以及我为什么会遇到这个问题。
错误与下一段代码中的私有(private)函数有关:
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;
}
});
}
}
最佳答案
我猜你的项目有某种类型的 linting 设置,可以在构建时检查样式问题。
要修复它,您只需要按照它说的去做。将代码移至任何方法调用之前。
export class HomeComponent implements OnInit {
public error: string;
public shirts = [];
private sizeScore = {
'string': -1,
s: 0,
m: 1,
l: 2,
'x-large': 3,
};
// ...
关于javascript - 这个错误 "Declaration of instance field not allowed after declaration of instance method."是什么意思,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45514843/