[英]listings is undefined angular2
我在組件內部聲明了一個變量,如下所示:
public listings: ListingSeller[];
正在從api獲取數據,並在OnInit中使用foreach將數據推送到上述數組,但它表示清單未定義。
this.eventService.getListingsByEventId(this.eventId).subscribe(listresults => {
this.bindListing(listresults);
}, error => this.errorMessage = error);
}
bindListing(listres: any[]) {
listres.forEach(function (data) {
data.ticket.seating.forEach(function(seat:any) {
this.listings.push(data);
});
})
}
您已定義類型,但未創建實例,因此您仍無法推送到該實例,因為該引用仍未定義。
public listings: ListingSeller[] = [];
將解決問題。 (添加= [];
),因為這將創建一個空數組。
另外你需要使用一個箭頭的功能 ,使this
指向該代碼正在執行中,而不是瀏覽器窗口中正確的實例。
this.eventService.getListingsByEventId(this.eventId).subscribe(listresults => {
this.bindListing(listresults);
}, error => this.errorMessage = error);
}
bindListing(listres: any[]) {
listres.forEach((data) => { // use arrow function HERE
data.ticket.seating.forEach((seat:any) => { // AND HERE
this.listings.push(data);
});
})
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.