如何在客户端映射对象(DTO)? [英] How to map objects (DTO) on client side?
问题描述
- 打字稿
- ABP + .NET Core
我正在使用网格插入行(我正在使用的网格是DevExtreme框架的组件).无论如何,与其他网格类似,当插入记录时,它会引发onRowInserting
事件,并提供插入的行作为参数.在这种情况下,我需要将该匿名"对象(插入的数据)转换为我的客户端DTO.
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:
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
内容(目前,我仅向网格中添加了一些列,因此并不存在所有字段).
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....
}
此图像更好地表示了对象: https://imgur.com/ihVZrDh
This image represents the object better: https://imgur.com/ihVZrDh
我不确定在let mynewrow: ItemDto
行中做了什么.
我不知道它是否正确,或者是否足以在以后使用该变量,然后将其传递给保存新行的服务.
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.
推荐答案
您可以使用装饰器和序列化器.请在此处查看ts的lib: https://www.npmjs.com/package/serialize-ts
You can use decorators and serializers. See lib for ts here: https://www.npmjs.com/package/serialize-ts
这篇关于如何在客户端映射对象(DTO)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!