arrays - Sum of arrays of objects withe pipe transform Angular
问题描述
I have list of objects with totaltime (there are other properties in objects
delayCount = { "delays": [ { "centre": "AAAA", "cause": "G - Capacity", "totalTime": 0 }, { "centre": "BBBB", "cause": "S - Staffing", "totalTime": 303 }, { "centre": "CCCC", "cause": "C - Capacity", "totalTi in arrayme": 34 } ] }
I am looking for smart pipe transform that would sum "totaTime", I used this code:
import { NgModule, Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'sum'
})
export class SumPipe implements PipeTransform {
transform(items: number[], attr: string): number {
// @ts-ignore
return items.reduce((a, b) => a + b[attr], 0);
}
and in the component HTML I used this :
{{ delayCount$ | async | sum:'totalTime'}}
And I had this error :
Argument type ListCount is not assignable to parameter type number[]
PS: ListCount is model :
export interface ListCount {
centre?: string;
cause?: string;
totalTime?: number;
}
Any help please
解决方案
According to the data you have provided, there are two problems
- You should pass "delays" field of your object
{{ (delayCount$ | async).delays | sum:'totalTime' }}
- Adjust pipe to get the right type
export class SumPipe implements PipeTransform {
transform(items: ListCount[], attr: string): number {
// @ts-ignore
return items.reduce((a, b) => a + b[attr], 0);
}
And do not use ts-ignore
推荐阅读
- android - 如何检查电话号码是否是Android中有效的whatsapp号码?
- python - 如何修复奇怪的模型精度图?
- python - 从 pandas 读取一个大的 CSV 文件后,我在我的工作簿中得到了一个荒谬的文件输出
- python - 熊猫:融化具有相同索引的多个列
- laravel - Git - 用新版本替换 Laravel 安装
- coldfusion - Lucee cfmail 消息 ID
- sprite - 如何在godot上做复合精灵
- javascript - Cypress 捕获所有请求 cy.Route()
- android - 在 LeakCanary 泄漏跟踪中查找原因
- django - 扩展 AbstractUser 后 Django 未创建用户