从JSON响应对象在Angular中创建一个类

时间:2017-02-06 18:20:46

标签: javascript json angular typescript

我想从以下响应模板为我的Angular App创建一个模型/类:

{
 "id": {integer},
 "name": {string},
 "make": {
       "id": {integer},
       "name": {string},
       "niceName": {string}
 },
 "model": {
   "id": {string},
   "name": {string},
   "niceName": {string}
 },
 "year": {
   "id": {integer},
   "year": {integer}
 },
 "submodel": {
   "body": {string},
   "fuel": {string}, // is not always populated
   "tuner": {string}, // is not always populated
   "modelName": {string},
   "niceName": {string}
 },
 "trim": {string},
 "states": {array},
 "engine": {object},
 "transmission": {object},
 "options": [
   {
     "category": {string},
     "options": {array}
   }
 ],
 "colors": [
   {
  "category": {string},
  "options": {array}
  }
  ],
 "drivenWheels": {string},
 "numOfDoors": {string},
 "squishVins": {array},
 "categories": {object},
 "MPG": {object},
 "manufacturerCode": {string},
 "price": {object}
 }

这样的事情:

class SearchResult {
 id: number;
 name: string;
 make: {
  id: number;
  name: string;
  niceName: string;
 };
 model: {
  id: number;
  name: string;
  niceName: string;
 };
 year: {
  id: number;
  year: number;
 }; 

一些警告:

  1. 这些字段中的大多数都有多个"对象/数据"为"颜色" (内部和外部)和选项(5个不同的类别) - 我如何构建一个'摘要'可以处理可变数量颜色的循环,等等。

  2. 某些字段返回一个对象 - 我该如何处理?

  3. 采取"模型"例如 - 它是一个包含3个字段的对象,' make'和'子模型'很相似。我该如何设置?

1 个答案:

答案 0 :(得分:2)

您可以将这些对象制作成模型!

所以你给出的例子如下:

r = s + rnorm(length(s))

对于灵长类动物或对象的数组,语法为:

import {Make, Model, Year} from "../my_models";

class SearchResult {
 id: number;
 name: string;
 make: Make;
 model: Model;
 year: Year;