繁体   English   中英

如何在Angular2中通过字符串插值遍历计数字段和全部字段以及输出

[英]How Would I Iterate Over Count Fields and Total Them And Output Via String Interpolation in Angular2

我正在使用Angular 2的* ngFor和字符串插值来遍历子字段并将它们与每个子字段的“计数”一起打印到屏幕上。 这是数据库上数据的样子:

[
  {
    "_id": {
      "status": "gold",
      "sub": "Category A"
    },
    "count": 19
  },
  {
    "_id": {
      "status": "gold",
      "sub": "Category B"
    },
    "count": 27
  },
  {
    "_id": {
      "status": "gold",
      "sub": "Category C"
    },
    "count": 24
  },
  {
    "_id": {
      "status": "",
      "sub": "Category D"
    },
    "count": 11
  }
]

这就是我在视图中将它们打印到屏幕上的方式:

<ul class="action-list">
    <li *ngFor="let record of records" class="action">{{record._id.sub}}<span class="action-counts">{{record.count}}</span></li>
</ul>

在我的组件中,我以这种方式调用计数服务:

ngOnInit() {
    this.streamGoldCountsService.getCount()
        .subscribe(resRecordsData => this.records = resRecordsData,
        responseRecordsError => this.errorMsg = responseRecordsError);
}

到目前为止,一切都按预期进行。

我的问题是,我将如何总计这些不同的子计数,然后将总计打印到屏幕上? 我们的数据库中没有子类别的总数,因此我将需要在组件中进行一些数学运算。 但是我不确定如何最好地做到这一点。 有什么想法吗?

您可以按照以下方式遍历记录:

  totalCounts(data) {
    let total = 0;

    data.forEach((d) => {
      total += parseInt(d.count, 10);
    });

    return total;
  }

这是一个小例子: https ://embed.plnkr.co/IylOI2JMwCpGyhmgJCUq/

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM