繁体   English   中英

列表未定义angular2

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM