首页 > 解决方案 > 从数组中的多个对象添加多个时间,并在 HTML 中使用 Angular 5 中的管道显示

问题描述

在对象数组中,我在嵌套数组中有多个对象,每个对象都有自己的时间值,例如 ""call_duration": "0:21"" ,我想添加所有时间并从 HTML 端以适当的时间格式显示它。数组是

[
  {
    "phone_number": "1905",
    "interactions": [
      {
        "agentId": "hassan1",
        "call_duration": "0:21"
      },
      {
        "agentId": "shabber",
        "call_duration": "1:22"
      }
    ]
 }
]

我想添加那些通话时间并显示最后的时间,所有的事情都应该在 HTML 中处理

标签: angulartypescript

解决方案


仅通过 HTML 很难获得总时间。

我建议你在 javascript 中使用一个函数来获取总时间。如下所示:

HTML

...
<div *ngFor="let item of data ">
      Phone: {{item.phone_number}} - Total Duration {{totalDuration(item.interactions)}}
</div>
...

TS

...
totalDuration(interactions: { 'agentId': string, 'call_duration': 'string' }[]) {
    let totalDuration = 0;
    interactions.forEach(item=>{
      // fetch seconds
      const seconds = +item.call_duration.split(':')[1];
      // fetch minutes and convert them into seconds
      const minutes = +item.call_duration.split(':')[0];
      const secondsOfMinutes = minutes * 60;
      // add all seconds
      totalDuration += seconds + secondsOfMinutes;
    })
    // convert totalDuration to readable format
    return Math.floor(totalDuration / 60) + ":" + (totalDuration % 60 ? totalDuration % 60 : '00')
  }
...

我还在stackblitz上创建了示例。


推荐阅读