2017-08-04 42 views
2

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

https://palantir.github.io/tslint/rules/member-ordering/ – arthurakay

+0

這意味着錯誤的語法。 –

回答

4

我猜想,你的項目有一些類型的掉毛設立,對於在編譯的時候作風問題檢查。

要解決它,你只需要按照說明來做。將代碼移至任何方法調用之前。

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

但是這對代碼運行有什麼影響?或者這是執行最佳實踐的問題嗎? – 2018-01-13 04:27:12

+2

不,它對代碼的操作沒有影響。 linter正在執行代碼樣式最佳實踐。 – DeborahK

1

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

將您的課程的所有屬性放在方法上方是一種很好的做法,因此如果您只是將private sizeScore移至頂端,它將停止說出。

有關此規則的更多信息here

0

根據TSLint docs我認爲你只需要將你的字段聲明移到這些方法的聲明之上。