【问题标题】:Angular 2, Unable to iterate through arrayAngular 2,无法遍历数组
【发布时间】:2017-11-20 23:23:52
【问题描述】:

我订阅了 FirebaseObjectObservable,以便从我的 firebase 数据库中获取对象的属性值。该属性可以包含多个值,因此我将这些值存储在本地数组变量中。

但我无法使用 forEach 遍历这个局部数组变量。所以我 console.log 这个数组变量。这个变量似乎有 json 格式,也许这就是我无法迭代的原因。请帮我找到一种方法来遍历这个变量。

* 代码和控制台图像:

Code Screenshot

Console Screenshot

* 编辑 *

我将 subscribe 方法中的代码转移到迭代。

getAttachments() {
this.assignment.subscribe(asnDetails => {
  if (asnDetails.fileKey) {
    this.fileKeys.push(asnDetails.fileKey);
    this.fileKeys[0].forEach(asnFileKey => {  // <---- shifted this forEach loop inside subscribe 
      this.asnFiles = this._getAsnService.getAssignmentFiles(asnFileKey);
      this.asnFiles.subscribe(file => {
        this.fileNames.push(file.name);
      });
    });
  }
});
}

【问题讨论】:

  • 请在问题中输入相关代码。另外,请用正确的国际英语书写,其中“I”一词大写。最后,请不要详细说明您在学习曲线中的位置,或者您对未来答案的感激之情。

标签: angular typescript firebase firebase-realtime-database rxjs


【解决方案1】:

this.fileKeys 值仅在 subscribe 处理程序中可用。这是异步编程的基础。您的控制台日志在订阅之后立即执行,并在订阅发生更改之前执行。

【讨论】:

    【解决方案2】:

    您的屏幕截图中有一个嵌套数组。第一个长度为 1,嵌套的长度为 2。这样你就可以访问array[0].forEach(item =&gt; console.log(item))

    【讨论】:

    • this.fileKeys[0].forEach( item =&gt; { console.log(item); }); 刚刚尝试过,得到了这个错误:未捕获(承诺中):TypeError:无法读取未定义的属性“forEach” TypeError:无法读取未定义的属性“forEach”... .
    【解决方案3】:

    很遗憾,我无法发表评论。这不是角度或火力问题。
    根据您的控制台屏幕截图,这是一个普通数组。
    您是否尝试过遍历this.fileKeys
    如果有人可以将此作为评论发布,我会将其作为答案删除。

    【讨论】:

    • 是的,我尝试迭代 this.fileKeys 但它似乎没有进入循环。 this.fileKeys.forEach( x =&gt; { console.log("Iterating..."); });
    • 你可以发console.log(this.fileKeys.length)) 并发布结果吗?
    • console.log(this.fileKeys.length) 返回 0
    • 如果在订阅中使用,则为 1
    猜你喜欢
    • 2016-09-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-07
    • 2017-11-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多