具有管道变换的对象数组的总和 Angular
Sum of arrays of objects withe pipe transform Angular
我有包含总时间的对象列表(对象中还有其他属性
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 } ] }
我正在寻找可以对“totaTime”求和的智能管道转换,我使用了以下代码:
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);
}
在组件 HTML 中我使用了这个:
{{ delayCount$ | async | sum:'totalTime'}}
我遇到了这个错误:
Argument type ListCount is not assignable to parameter type number[]
PS:ListCount 是模型:
export interface ListCount {
centre?: string;
cause?: string;
totalTime?: number;
}
请帮忙
根据您提供的数据,存在两个问题
- 您应该传递对象的“延迟”字段
{{ (delayCount$ | async).delays | sum:'totalTime' }}
- 调整管道以获得正确的类型
export class SumPipe implements PipeTransform {
transform(items: ListCount[], attr: string): number {
// @ts-ignore
return items.reduce((a, b) => a + b[attr], 0);
}
并且不要使用 ts-ignore
我有包含总时间的对象列表(对象中还有其他属性
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 } ] }
我正在寻找可以对“totaTime”求和的智能管道转换,我使用了以下代码:
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);
}
在组件 HTML 中我使用了这个:
{{ delayCount$ | async | sum:'totalTime'}}
我遇到了这个错误:
Argument type ListCount is not assignable to parameter type number[]
PS:ListCount 是模型:
export interface ListCount {
centre?: string;
cause?: string;
totalTime?: number;
}
请帮忙
根据您提供的数据,存在两个问题
- 您应该传递对象的“延迟”字段
{{ (delayCount$ | async).delays | sum:'totalTime' }}
- 调整管道以获得正确的类型
export class SumPipe implements PipeTransform {
transform(items: ListCount[], attr: string): number {
// @ts-ignore
return items.reduce((a, b) => a + b[attr], 0);
}
并且不要使用 ts-ignore