列表未定义angular2

时间:2017-02-21 19:00:16

标签: javascript angular typescript

我在组件内声明了一个变量,如下所示,

public listings: ListingSeller[];

从api获取数据并使用foreIn内部的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);
            });
        })
    }

1 个答案:

答案 0 :(得分:1)

您定义了类型,但没有创建实例,因此您仍然无法推送它,因为引用仍未定义。

public listings: ListingSeller[] = [];

将解决问题。 (添加= [];)因为这会创建一个空数组。

此外,您需要使用arrow function,以便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);
            });
        })
    }