【问题标题】:"Hydrate" class instance from JSON object来自 JSON 对象的“Hydrate”类实例
【发布时间】:2019-01-19 21:58:37
【问题描述】:

我有这门课:

import { AccountRow } from './account-row';
export class Account {
  id?:number;
  name:string;
  rows: AccountRow[];
  public getTotal?(): number {
    let total: number = 0;
    if (!this.rows || this.rows.length == 0) {
      return total;
    }
    for(let r of this.rows) {
      total += r.amount;
    }
    return total;

  }
}

我尝试用以下内容填充它:

export class HomePage {
  accountForm: FormGroup;
  addRowForm: FormGroup;
  activeAccount: Account;

  constructor(public navCtrl: NavController) {
    // fixture for testing
    this.activeAccount = {
      name: "January balance",
      rows: [
        { description: "Car insurance", amount: 45.5, date: new Date() },
        { description: "Car insurance", amount: -20.5, date: new Date() }
      ]
    };
    console.log(this.activeAccount.getTotal());

  }
}

值已正确分配,但似乎对象分配正在破坏 getTotal 方法,当我执行它抛出的代码时:

Error: Uncaught (in promise): TypeError: this.activeAccount.getTotal is not a function
TypeError: this.activeAccount.getTotal is not a function

我想知道是否可以在不破坏实例方法并且不实现初始化构造器或工厂方法的情况下做到这一点

【问题讨论】:

  • 你不是在实例化 Accountobject 而是一个 Object 字面量,你在期待什么?
  • @n00dl3 我只是想问是否有办法像 c# 那样做:new Account() { ... }。只是一些语法糖

标签: angular typescript class-transformer


【解决方案1】:

没有办法在语言中做到这一点。使用类转换器 https://github.com/pleerock/class-transformer.

【讨论】:

  • 谢谢,我试试
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-03-14
  • 1970-01-01
  • 2018-08-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多