如何使用api响应Angular 5映射模型类

时间:2018-10-10 08:55:38

标签: angular model mapping

我有一个api响应:

{
 "response_type": 1,
 "msg": "",
 "success": true,
 "status": 200,
 "data": {
   "first_name": "Divyashree M",
   "user_id": 258031,
   "svc_id": 2,
   "svc_name": "21North India",
   "address": {
    "country": "india",
    "street_name": "queens road",
    "locality": "not defined",
    "door_number": "0",
    "zipcode": "pipoi--"},
   "logo_url": "url",
   "permission_type_id": 1,
   "is_admin": 0,
   "company_type": 1,
   "designation_id": 1,
   "term_status": 0
 }
}
我创建的

界面是:

interface RootObject {
  response_type: number;
  msg: string;
  success: boolean;
  status: number;
  data: Data;
}

interface Data {
  first_name: string;
  user_id: number;
  svc_id: number;
  svc_name: string;
  address: Address;
  logo_url: string;
  permission_type_id: number;
  is_admin: number;
  company_type: number;
  designation_id: number;
  term_status: number;
}

interface Address {
  country: string;
  street_name: string;
  locality: string;
  door_number: string;
  zipcode: string;
}

谁能告诉我如何将json与模型类进行映射,以及如何检查具有类所有属性的api是否来自正确的数据类型。我尝试使用Rxjs中的map函数,但遇到问题。请帮帮我。

1 个答案:

答案 0 :(得分:0)

我们需要了解更多信息以帮助您。您如何调用您的API?它是可观察的吗?

我看到API响应和接口具有相同的结构。 尝试像这样向每个模型中添加构造函数:

    export class RootObject {

      constructor(obj: any) {
         _.assignin(this, obj);
      }

      response_type: number;
      msg: string;
      success: boolean;
      status: number;
      data: Data;
    }

    export class Data {

      constructor(obj: any) {
         _.assignin(this, obj);
      }

      first_name: string;
      user_id: number;
      svc_id: number;
      svc_name: string;
      address: Address;
      logo_url: string;
      permission_type_id: number;
      is_admin: number;
      company_type: number;
      designation_id: number;
      term_status: number;
    }

export class Address {

      constructor(obj: any) {
         _.assignin(this, obj);
      }

      country: string;
      street_name: string;
      locality: string;
      door_number: string;
      zipcode: string;
    }

如果通过HTTP获得API响应,则应该是这样的:

let rootObject: RootObject;
this.http.get(url, options).subscribe(data => rootObject = new RootObject(data));