How to map objects (DTO) on client side?

て烟熏妆下的殇ゞ 提交于 2019-12-11 09:52:00

问题


  • Typescript
  • ABP + .NET Core

I'm using a grid to insert rows (the grid I'm using is a component of the DevExtreme framework). Anyway, similar to other grids, it raises onRowInserting events when the records are inserted, providing the inserted row as a parameter. I need to convert that "anonymous" object (the inserted data) to my client-side DTO in this event.

onRowInserting(e) {
    let mynewrow: ItemDto = e.data; // e.data contains the inserted row
}

To better understand what I need to achieve, please read this post:

Add rows to DevExtreme grid (angular) - model/schema

EDIT

The ItemDto:

export class ItemDto implements IItemDto {
    description: string;
    note: string;
    quantita: number;
    postId: number;
    id: number;

    constructor(data?: IItemDto) {
        if (data) {
            for (var property in data) {
                if (data.hasOwnProperty(property))
                    (<any>this)[property] = (<any>data)[property];
            }
        }
    }

    init(data?: any) {
        if (data) {
            this.description = data["description"];
            this.note = data["note"];
            this.quantita = data["quantita"];
            this.postId = data["postId"];
            this.id = data["id"];
        }
    }

    static fromJS(data: any): ItemDto {
        let result = new ItemDto();
        result.init(data);
        return result;
    }

    toJSON(data?: any) {
        data = typeof data === 'object' ? data : {};
        data["description"] = this.description;
        data["note"] = this.note;
        data["quantita"] = this.quantita;
        data["postId"] = this.postId;
        data["id"] = this.id;
        return data; 
    }

    clone() {
        const json = this.toJSON();
        let result = new ItemDto();
        result.init(json);
        return result;
    }
}

export interface IItemDto {
    description: string;
    note: string;
    quantita: number;
    postId: number;
    id: number;
}

And below, the content of e.data (at this moment, I've added only some columns to the grid, so not all fields are present).

Object {
    __KEY__: "7c2ab8-1ff6-6b53-b9d7-ba25c27"
    description: "mydescription"
    id: 32
    note: "mynote"
    postId: 4
    quantita: 2
     >  __proto__: Object { constructor; , _defineG....
}

This image represents the object better: https://imgur.com/ihVZrDh

I'm not sure what I did in the line let mynewrow: ItemDto. I don't know if it is correct, or if it is enough to use the variable later, passing it to the service that saves the new row.


回答1:


You can use decorators and serializers. See lib for ts here: https://www.npmjs.com/package/serialize-ts



来源:https://stackoverflow.com/questions/48802922/how-to-map-objects-dto-on-client-side

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!