我有这个代码从MongoDB获取一些数据并将其保存在我的组件中的数组中。
this.laugService.getAllLaug().subscribe(laug => {
this.laugs = laug; //save posts in array
});
this.laugs.array.forEach(element => {
this.modelLaugs.push(new Laug(element.navn, element.beskrivelse))
});
之后我想将这些数据保存到不同的数组,在那里我创建了我的模型的新实例" Laug"。为此,我使用的是foreach循环,但运行此代码时出现错误:
ERROR Error: Uncaught (in promise): TypeError: Cannot read property
'forEach' of undefined
TypeError: Cannot read property 'forEach' of undefined
我确信我收到了来自数据库的数据,但我不确定为什么我的数组在此时未定义。
答案 0 :(得分:1)
您的订阅异步。在尝试迭代时,可能无法设置 laugs 属性。只需将forEach代码放在subscribe回调中:
this.laugService.getAllLaug().subscribe(laug => {
this.laugs = laug; //save posts in array
if (this.laugs && this.laugs.array) {
this.laugs.array.forEach(element => {
this.modelLaugs.push(new Laug(element.navn, element.beskrivelse))
});
}
});