从数组中的多个对象添加多个时间,并在 HTML 中使用角度 5 中的管道显示



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

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

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

仅通过 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')
  }
...

我还在堆栈闪电战上创建了示例。

假设你有一个这样的数组:

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

要显示此数据,您可以使用嵌套循环,例如:

<div *ngFor="let data of myObject ">
      Phone: {{data.phone_number}} - Intractions <span *ngFor="let intrac of data.interactions">{{intrac.call_duration}}</span>
</div> 

嵌套循环遍历您的交互数组。

最新更新