Angular, foreach into subscribe



我需要从订阅的数据结果构建一个数组。

现在我有这个:

const dataFormat = new IData();
this.api.getData()
.pipe(
map(response => response),
tap(data => console.log('data array', data)))
.subscribe(dataResult => {
dataResult.forEach(function (item) {
dataFormat.title = item['title'];
dataFormat.author = item['author'];
dataFormat.date = item['date'];
this.listData.push(dataFormat);
});
});

this.listData.push中,我有以下错误:Potentially invalid reference access to a class field via 'this.' of a nested function

如果我将let self = thisself.listData.push(dataFormat);一起使用,则我的数组只存储foreach中的最后一项。

我认为有一个作用域错误forEach也知道这类错误

您应该使用一个普通的for循环,而不是forEach循环。

.subscribe(dataResult => {
for(let item of dataResult) {
dataFormat.title = item['title'];
dataFormat.author = item['author'];
dataFormat.date = item['date'];
this.listData.push(dataFormat);
}
});

或者,如果您仍然想坚持forEach循环,请传递一个箭头函数:

.subscribe(dataResult => {
dataResult.forEach(item => {
dataFormat.title = item['title'];
dataFormat.author = item['author'];
dataFormat.date = item['date'];
this.listData.push(dataFormat);
});
});

最新更新