首页 > 解决方案 > 对象 typescript/ionic 3 的接口

问题描述

我有一个从 api 返回的 json 对象,并希望创建一个包含该对象包含的字段的接口。我正在使用 ionic 3 框架。我需要有关如何创建此接口的帮助。(我很困惑:我应该为数据创建另一个接口吗?如果是,如何将其包含在主界面中?)对象结构如下:

{

"status": "success",

"data": [

      {

          "id": 113,

          "subject": "hello there",

          "body": "i am hisham",

          "sender": {

              "id": 51,

              "country": {

                  "id": 9,

                  "name_en": "Syria",

              }

          }

      },

      {

          "id": 114,

          "subject": "hello there",

          "body": "i am lkfdj",

          "sender": {

              "id": 54,

              "country": {

                  "id": 9,

                  "name_en": "Syria",
              }

          }

      }

  ]

}

标签: javascripttypescriptionic-frameworkionic3

解决方案


如果要定义接口,则应为响应中的每个对象定义一个。您不必这样做,但要获得正确的类型完成,您应该这样做。

interface Response {
  status: string;
  data: Data[];
}

interface Data {
  id: number;
  subject: string;
  body: string;
  sender: Sender;
}

interface Sender {
  id: number;
  country: Country;
}

interface Country {
  id: number;
  name_en: string;
}

推荐阅读