Javascript 列表未定义角度2

Javascript 列表未定义角度2,javascript,angular,typescript,Javascript,Angular,Typescript,我在组件中声明了一个变量,如下所示 public listings: ListingSeller[]; 我从一个api获取数据,并在OnInit中使用foreach推送到上面的数组,但它说列表是未定义的 this.eventService.getListingsByEventId(this.eventId).subscribe(listresults => { this.bindListing(listresults); }, error =&g

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

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.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.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);
            });
        })
    }

它不起作用,无法读取的属性“列表”undefined@user2280016-请参阅更新,您需要使用
箭头
函数或获取对
的引用,以便在
函数
内部使用。使用ListingSeller界面属性更新帖子