【问题标题】:get sum of value from object Typescript从对象 Typescript 中获取值的总和
【发布时间】:2018-03-07 11:39:44
【问题描述】:

我有这个数据,

    [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, …}

我想sum(Subtotal) 使用这个功能,但在 html 中什么也不显示

 products: Products[] = [];

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

html代码:

<label for="total">Totale: {{total}} </label> --> show nothing
<label for="total">{{cartTotal(total)}}Totale: ALL</label>  --> show NaN

【问题讨论】:

  • 您的数据显示Subtotal,但您的代码显示subtotal 这只是问题中的拼写错误,还是实际问题?

标签: html angular typescript calculator


【解决方案1】:

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

你必须把它改成这个

@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;
    }
}

编辑

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

&lt;label for="total"&gt;{{cartTotal(total)}}Totale: ALL&lt;/label&gt; 将进行多次角度调用cartTotal(在每个更改检测周期)。您不会想通过products 数组并进行数千次计算。

【讨论】:

  • 如何在html中显示这个?
  • Totale: {{tempTotal}} --> 什么都不显示 {{cartTotal(tempTotal)}}Totale --> 显示 NaN
  • 是的,但对我来说,我现在不知道为什么不起作用。也许,因为我的小计是形成这个结果: 跨度>
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-01-31
  • 1970-01-01
  • 2016-05-11
  • 2022-01-02
  • 2021-09-29
  • 2022-01-07
相关资源
最近更新 更多