在后端和前端之间对模型进行反序列化和序列化模型(Angular 6)



>有没有更好的方法可以做到这一点?我想为每个模型创建一个方法,我必须对其进行序列化以传输到后端。

某些属性将以 ID 的形式从后端进入应用程序,前端将在对象存储中查找该 ID。

我希望 SerializedAnswer 接口能够具有用户和类型编号的问题,但我必须创建一个新的 Answer 父接口才能允许多种类型。

我最初想做的是:

interface SerializedAnswer extends Answer {
inventory: number;
question: number;
user: number;
}

这将给出以下错误:

[ts]
Interface 'SerializedAnswer' incorrectly extends interface 'Answer'.
Types of property 'inventory' are incompatible.
Type 'number' is not assignable to type 'Inventory'.

这有效,但似乎有点麻烦和重复:

import { User } from './user';
import { Question } from './question';
interface AnswerInterface {
id: number;
user: User | number;
question: Question | number;
response: number;
}
interface SerializedAnswer extends AnswerInterface {
id: number;
user: number;
question: number;
response: number;
}
class Answer {
id: number;
user: User;
question: Question;
response: number;
serialize(): SerializedAnswer {
return Object.assign(this, {
user: this.user.id,
question: this.question.id
});
}
}

我希望能够在服务中做这样的事情:

function getAnswer(id: number): Observable<Answer> {
this._apiService.get<SerializedAnswer>(['answer', id]).pipe(map(res => {
return new Answer({
...res,
... { user: this._userService.find(res.user) },
... { question: this._questionService.find(res.question) }
});
}));
}
function saveAnswer(answer: Answer): Observable<Answer> {
return this._apiService.post(['answer', 'save'], answer.serialize());
}

我发现这在带有声明合并的打字稿中是可能的。

https://www.typescriptlang.org/docs/handbook/declaration-merging.html

您可以拥有与类同名的接口,这允许您创建一个类,该类自动实现它实现的接口的所有属性。

interface AnswerInterface {
id: number;
createdAt?: number;
updatedAt?: number;
inventory: Inventory | number;
question: Question | number;
user: number;
response: number; // 1 = Strongly Disagree, 4 = Strongly Agree
}
export interface SerializedAnswer extends AnswerInterface { }
export class SerializedAnswer implements AnswerInterface {
inventory: number;
question: number;
}
export interface Answer extends AnswerInterface { }
export class Answer implements AnswerInterface {
inventory: Inventory;
question: Question;
public constructor(init?: Partial<Answer>) {
Object.assign(this, init);
}
serialize(): SerializedAnswer {
return Object.assign(this, {
question: this.question.id,
inventory: this.inventory.id
});
}
}

相关内容

最新更新