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

时间:2018-06-06 14:26:03

标签: javascript angular typescript

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

某些属性将以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());
}

1 个答案:

答案 0 :(得分:0)

我发现这可以在带有声明合并的Typescript中实现。

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