问题
- 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