【问题标题】:How to write json pie angular get properties?如何编写 json pie 角度获取属性?
【发布时间】:2021-11-02 14:28:34
【问题描述】:

我的 Angular 项目中有一个打字稿类。

export class CheckoutInfo {
    lines: CheckoutInfoLine[];
    taxRate: number;

    get subTotal(): number {
        return this.lines.reduce((acc: number, cur: CheckoutInfoLine) => acc + cur.total, 0)
    };

    get taxTotal(): number {
        return this.subTotal * this.taxRate;
    }

    get grandTotal(): number {
        return this.subTotal * (1 + this.taxRate);
    }

    constructor(lines: CheckoutInfoLine[] = [], taxRate: number = 0.7) {
        this.lines = lines;
        this.taxRate = taxRate;
    }
}

我想使用如下管道编写此对象:

{{ myObject | json }}

但是get参数(subTotal,grandTotal,taxTotal)没有写入json字符串:

{ 
  "lines": [ 
   { "amount": "2", "product": { "id": 6, "name": "p-1", "price": 115.798 } }, 
   { "amount": 1, "product": { "id": 1, "name": "p-2", "price": 0 } } 
  ], 
  "taxRate": 0.7 
}

【问题讨论】:

    标签: angular angular-pipe angular-json


    【解决方案1】:

    这是预期的,因为这些属性默认情况下不会序列化。如果你真的需要这种行为,我建议你重写 toJSON 方法

    export class CheckoutInfo {
      toJSON() {
        return {
          ...this,
          subTotal: this.subTotal,
          taxTotal: this.taxTotal,
          grandTotal: this.grandTotal,
        };
    
      }
    

    【讨论】:

      猜你喜欢
      • 2019-08-28
      • 1970-01-01
      • 2017-11-10
      • 1970-01-01
      • 1970-01-01
      • 2023-01-06
      • 2015-03-12
      • 2016-01-20
      • 1970-01-01
      相关资源
      最近更新 更多