打字稿强调案例翻译

时间:2017-03-29 21:39:11

标签: angular typescript

我正在使用我的域类:

export class Contact {

  private _name: string;
  private _phone: string;

  get name(): string {
    return this._name;
  }

  set name(value: string) {
    this._name = value;
  }

  get phone(): string {
    return this._phone;
  }

  set phone(value: string) {
    this._phone = value;
  }

}

我的问题是当我通过角度http.post向后端发送数据时,发送的属性是带有下划线的属性,我的后端只为camelCase准备(更改后端可能不是这里的选项)。除了在发送之前翻译JSON之外还有其他已知的选项吗? 提前谢谢。

1 个答案:

答案 0 :(得分:3)

您有两种方法可以做到这一点:

1)在toJSON()类上定义Contact函数:

public toJSON() {
    return {
        name: this._name,
        phone: this._phone,
    };
}

2)使用JSON.stringify(...)替换第二个参数:

let serialized = JSON.stringify(contact, Object.keys(contact.constructor.prototype))
  

了解更多:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify

相关问题