来自JSON对象的“Hydrate”类实例

时间:2017-05-22 10:36:24

标签: angular typescript class-transformer

我有这堂课:

Ext.define('MyApp.Application', {
    ...
    init: function() {
        // SUSPEND APP LOADING
        Ext.Ajax.request({
            ...
            success: function() { 
                // CONTINUE app loading 
            }
        })
    }
});

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

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;

  }
}

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

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());

  }
}

我想知道是否可以在不破坏实例方法且不实现初始化构造函数或工厂方法的情况下执行此操作

1 个答案:

答案 0 :(得分:0)

用语言无法做到这一点。使用class-transformer https://github.com/pleerock/class-transformer