首页 > 解决方案 > 使用字母数字 ID 遍历 Firebase 子数组

问题描述

我使用 post 请求将数据存储在 firebase 实时数据库中,就像 JavaScript 中的 push() 一样。以前我的数据是以 JSON 格式导入的,注释按数字 id 排序。这对于对数据进行一些计算非常有帮助。现在,在转向 post 以允许用户提交他们对特定项目的评论和评分后,我无法执行相同的操作,因为评论的 id 现在是字母数字字符串。我得到的是未定义的评论数量和未定义的平均评分。

this.http.post(baseURL + 'dishes/' + this.dish.id + '/comments.json', this.comment)
  .subscribe(res => {
    console.log(res);
  })

我正在执行一些计算:

//this.dish.comments.push(this.comment);
this.numcomments = this.dish.comments.length;
this.dish.comments.forEach(comment => total += comment.rating);
this.avgstars = (total / this.numcomments).toFixed(2);

而且它们不再可用。我得到的是评论:未定义和平均星:未定义。

这是我的数据示例: 在此处输入图像描述

知道如何使用其字母数字 id 遍历 comments 数组以获取值并在计算时将它们正确呈现到 UI 吗?

我欢迎您的建议和更正。

谢谢,

标签: javascriptangularfirebasefirebase-realtime-database

解决方案


推荐阅读