angular - 如何在客户端映射对象(DTO)?

标签 angular typescript automapper aspnetboilerplate dto-mapping

  • typescript
  • ABP + .NET Core

我使用网格来插入行(我使用的网格是 DevExtreme 框架的组件)。不管怎样,与其他网格类似,它在插入记录时引发 onRowInserting 事件,并提供插入的行作为参数。我需要在此事件中将该“匿名”对象(插入的数据)转换为我的客户端 DTO。

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

为了更好地了解我需要实现的目标,请阅读这篇文章:

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

编辑

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;
}

下面是 e.data 的内容(此时,我只向网格添加了一些列,因此并非所有字段都存在)。

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

该图像更好地代表了该对象:/image/XkEB1.jpg

我不确定我在 let mynewrow: ItemDto 行中做了什么。 我不知道它是否正确,或者稍后使用该变量是否足够,将其传递给保存新行的服务。

最佳答案

您可以使用装饰器和序列化器。请参阅此处的 ts 库:https://www.npmjs.com/package/serialize-ts

关于angular - 如何在客户端映射对象(DTO)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48802922/

相关文章:

css - 更改所选选项卡的颜色,属于 TabMenu PRIMENG - 样式

《英雄》教程中的 Angular RXJS CatchError

c# - 可以使用 WCF + DTO + Automapper 吗?

angular - 选择器不反射(reflect) reducer 中的状态

c# - AutoMapper - 映射子列表时非常奇怪的行为

c# - 使用 ValueInjecter 扁平化对象,包括可空类型

javascript - 如何使我的 JS 解决方案发挥作用?

javascript - Angular-cli 出现错误

javascript - Google map /TypeScript - 无法一致识别 google.maps.Place

angular - 为什么我不能使用 Angular NgModel 限制输入的值长度?