简体   繁体   English

Angular 5.2.10-TypeScript 2.4.2属性accesor json映射

[英]Angular 5.2.10 - TypeScript 2.4.2 property accesor json mapping

I have a problem that I can't seem to find a solution for or maybe my search is wrong. 我有一个问题,我似乎找不到解决方法,或者我的搜索错误。 The problem is as follows: 问题如下:

Background 背景

I have an BookingEvent class that is defined as follows: 我有一个BookingEvent类,其定义如下:

export class BookingEvent {
    title: string;

    private _startDate: Date;

    set startDate(value: Date) {
        let valueMoment = moment(value);
        if (valueMoment.isValid()) this._startDate = valueMoment.toDate();

    }

    get startDate(): Date {
        return this._startDate;
    }

    private _endDate: Date;

    set endDate(value: Date) {
        let valueMoment = moment(value);
        if (valueMoment.isValid()) this._endDate = valueMoment.toDate();
    }
}

In addition to the above, I have a form component with a template doing two way binding to the properties. 除上述内容外,我还有一个带有模板的表单组件,该模板对属性进行两种方式的绑定。

Problem 问题

When I save the form data to a remote api, I realised that the json produced maps my startDate & endDate bound properties as _startDate & _endDate respectively as is evident from: 当我将表单数据保存到远程api时,我意识到生成的json将我的startDateendDate绑定属性分别映射为_startDate_endDate,以下所示:

{
        "title": "My awesome event",
        "_startDate": "2018-04-26T20:50:00.000Z",
        "_endDate": "2018-04-27T19:50:00.000Z"
    }

Question

Why is the native json mapper using the private property names as opposed to the public ones? 为什么本地json映射器使用私有属性名称而不是公共属性名称? How can I ensure that the public property name are used? 如何确保使用公共属性名称?

You can specify a toJSON() method to customize what the object looks like when it is serialized using JSON.stringify(...) . 您可以指定toJSON()方法,以自定义使用JSON.stringify(...)序列化对象时的外观。 That link details exactly how it figures out what to include in the object being serialized. 该链接详细说明了如何确定要序列化的对象中包括哪些内容。 JavaScript doesn't have the concept of private properties, so they are just properties like anything else. JavaScript没有私有属性的概念,因此它们就像其他任何属性一样。

class BookingEvent {
    // all the rest of your code

    toJSON() {
        return {
            title: this.title,
            startDate: this.startDate,
            endDate: this.endDate
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM