2017-12-27 472 views
1

我有一個列表,我只是想過濾。 Array.find和filter都會產生錯誤。Array.Filter和找不到錯誤角度4

功能:

setSupplierDetails(supplierId) { 
const supplier = this.suppliers.filter(tempSupplier => tempSupplier.id === supplierId)[0]; 
this.supplierName = supplier.supplierName; 

} 錯誤:

ERROR TypeError: Cannot read property 'filter' of undefined 
    at AddEditRestockComponent.webpackJsonp.../../../../../src/app/restock/add-edit-restock/add-edit-restock.component.ts.AddEditRestockComponent.setProductRelatedInfo 
+4

顯然,'this.suppliers'沒有被定義。確保它不僅被聲明,而且被初始化(例如'suppliers:SomeClass [] = [];')。 – ConnorsFan

+0

發佈'this.suppliers' –

+0

我找到了答案。我通過setSupplierDetails(supplierId)將supplierId作爲一個我意識到導致問題的數字。 setSupplierDetails(supplierId){供應商= this.suppliers.filter(tempSupplier => tempSupplier.id === + supplierId)[0]; this.supplierName = supplier.supplierName; – user3701188

回答

0

如果你的數組沒有初始化,這應該發生,以處理initalize您的陣列

suppliers: SomeClass[] = []; 

和內方法

setSupplierDetails(supplierId) { 
if(this.suppliers && this.suppliers.length > 0){ 
const supplier = this.suppliers.filter(tempSupplier => tempSupplier.id === supplierId)[0]; 
}