首页 > 解决方案 > 如何在角度 8 中为嵌套 JSON 创建模型文件

问题描述

我想在角度 8 中为嵌套 JSON 创建模型文件。因为我是 Angular Development 的新手,所以不知道该怎么做。

我的 Api 响应如下所示:

{
   "data": [{
      "nationalCustomerId": 31,
      "nationalCustomerName": "Family Dollar",
      "stores": [{
            "categories": [{
               "category": "Dairy",
               "categoryId": 1
            }],
            "storeId": 18627,
            "storeNumber": 3367
         },
         {
            "categories": [{
               "category": "Dairy",
               "categoryId": 1
            }],
            "storeId": 25540,
            "storeNumber": 10164
         },
         {
            "categories": [{
               "category": "Dairy",
               "categoryId": 1
            }],
            "storeId": 25735,
            "storeNumber": 10783
         },
         {
            "categories": [{
               "category": "Dairy",
               "categoryId": 1
            }],
            "storeId": 26971,
            "storeNumber": 11374
         }
      ]
   }],
   "status": "success"
}

任何帮助表示赞赏.. 我想为 Angular 8 中的上述 API 响应创建一个模型文件。

标签: javascriptjsonangular

解决方案


模型类可能如下所示:

export class Response {
    data: Customer[];
    status: string;
}

export class Customer {
    nationalCustomerId: number;
    nationalCustomerName: string;
    stores: Store[];
}

export class Store {
    storeId: number;
    storeNumber: number;
    categories: Category[];
}

export class Category {
    category: string;
    categoryId: number;
}

为了使它们井井有条,请将它们作为单独的文件并根据需要导入以引用它们,例如:

在名为 store.ts 的文件中(具有 Store 类定义):

//if your Category model class is in same folder and called category.ts
import { Category } from './category';

然后,您可以将外部“数据”类导入需要映射响应的文件,例如:

import { Response } from '<some path to your model classes folder>/response';

推荐阅读