首页 > 解决方案 > Angular - rest api json对模型的响应

问题描述

我如何将以下json响应转换为角度模型

{
  data: [
    {
      id: 3,
      country_id: 1,
      name: "name1",
      address: "address 1",
      isActive: 1,
      created_at: "2021-08-26T17:35:54.000000Z",
      updated_at: "2021-08-26T17:35:54.000000Z",
      country: {
        id: 1,
        name: "UAE",
      },
    },
  ],
  message: "success",
  status: true,
};

标签: angulartypescript

解决方案


我创建了几个接口和一个模型,它不是完整的代码,只是为了让您了解如何在 Angular 中创建数据模型类,希望对您有所帮助

export interface IResponse {
  status?: boolean;
  message?: string;
  data?: Array<IUser>;
}

export interface IUser {
  id?: number;
  country_id?: number;
  name?: string;
  address?: string;
  isActive?: number;
  created_at?: Date;
  updated_at?: Date;
  country?: ICountry;
}

export interface ICountry {
  id?: number;
  name?: string;
}

//===========================================================
// Model for above interface
//==========================================================
export class User {
  id: number;
  country_id: number;
  name: string;
  address: string;
  isActive: number;
  created_at: Date;
  updated_at: Date;
  country: ICountry;
  constructor(data?: IUser = null) {
    this.id = data?.id;
    this.country_id = data?.country_id;
    this.name = data?.name;
    this.address = data?.address;
    this.isActive = data?.isActive;
    this.created_at = data?.created_at;
    this.updated_at = data?.updated_at;
    this.country = data?.country;
  }
}


//===========================================================
// Suppose you have api method which will return this data
//==========================================================


ngOnInit() {
  let response: IResponse = fetchData(); 
  let userList: Array<User> = [];
  
  response?.data?.forEach((user) => {
    userList.push(new User(user)) 
  });
}

fetchData(): IResponse {
  return {
    data: [
      {
        id: 3,
        country_id: 1,
        name: "name1",
        address: "address 1",
        isActive: 1,
        created_at: "2021-08-26T17:35:54.000000Z",
        updated_at: "2021-08-26T17:35:54.000000Z",
        country: {
          id: 1,
          name: "UAE",
        },
      },
    ],
    message: "success",
    status: true,
  } as IResponse
}



推荐阅读