【问题标题】:Iterating over array created from subscribe function of Observable迭代从 Observable 的订阅函数创建的数组
【发布时间】:2017-10-30 14:27:24
【问题描述】:

我有这段代码从 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

我确定我收到了来自数据库的数据,但是我不确定为什么我的数组此时未定义。

【问题讨论】:

标签: arrays typescript


【解决方案1】:

您的订阅是异步。当您尝试迭代时,可能未设置 laugs 属性。只需将 forEach 代码放在订阅回调中即可:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-09-28
    • 2019-07-25
    • 1970-01-01
    • 2016-12-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-20
    相关资源
    最近更新 更多