首页 > 解决方案 > 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

标签: arraysangularpipereduce

解决方案


According to the data you have provided, there are two problems

  1. You should pass "delays" field of your object
{{ (delayCount$ | async).delays | sum:'totalTime' }}
  1. 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


推荐阅读