簡體   English   中英

這個錯誤的含義是什么?聲明實例方法后不允許聲明實例字段。

[英]What is the meaning of this error “Declaration of instance field not allowed after declaration of instance method.”

在我的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;
        }
    });
}
}

我猜你的項目有一些類型的linting設置,可以在構建時檢查樣式問題。

要解決它,你只需按照它說的那樣做。 在任何方法調用之前將代碼移動到。

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

它實際上不是編譯/運行時錯誤,而是代碼linting問題。

將您班級的所有屬性置於方法之上是一種很好的做法,因此如果您只是將private sizeScore移到頂部,它就會停止說。

關於這個規則的詳細信息在這里

根據TSLint文檔,我認為您只需將該字段的聲明移到這些方法的聲明之上。

現在不推薦使用public-before-privatestatic-before-instance

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM