从对象Typescript中获取值的总和

时间:2018-03-07 11:39:45

标签: html angular typescript calculator

我有这些数据,

.has-bg-secondary

我想 [Products, Products, Products, Products] 0: Products {product_id: "1", Product_type_id: "11", Subtotal:450, …} 1: Products {product_id: "2", Product_type_id: "22", Subtotal:550, …} 2: Products {product_id: "3", Product_type_id: "33", Subtotal:600, …} 3: Products {product_id: "4", Product_type_id: "44", Subtotal:100, …} 使用此功能,但在html中没有显示任何内容

sum(Subtotal)

html代码:

 products: Products[] = [];

  public cartTotal(): number {
    let total: number = 0;
    this.products.forEach((e: any) => {
        total = total + Number(e.subtotal);
    });
    return total;
}

1 个答案:

答案 0 :(得分:0)

当您尝试通过{{someVar}}从html访问变量时,如果存在名为someVar的属性,angular将查看其组件。您将从total返回cartTotal,但没有人在听。

您必须将其更改为此

@Component({
   selector: 'some-comp',
   template: `<label for="total">Totale: {{total}} </label>`
})
export class SomeComponent {
    total;

    // you have to call this method at some point, 
    // I omitted that part. I assume you already call it.
    public cartTotal(): number {
        let tempTotal: number = 0;
        this.products.forEach((e: any) => {
            tempTotal= tempTotal+ Number(e.subtotal);
        });
        this.total = tempTotal;
    }
}

修改

您不应直接从标记中调用方法。

<label for="total">{{cartTotal(total)}}Totale: ALL</label>这将使角度调用cartTotal这么多次(在每个更改检测周期)。您不希望通过products数组并进行数千次计算。