如何将嵌套的 json 对象映射到 angular 11 中的模型?

How to mapping nested json object to model in angular 11?

我想用嵌套对象填充 angular 中的人物 class 我的 api 回复是:

{
"id": "1001614505887752423",
"type": 1,
"name": "test contact",
"createdAt": "1399/12/10 - 09:51",
"updatedAt": "1399/12/10 - 09:51",
"addresses": [
  {
    "id": "1001614505887757358",
    "personId": "1001614505887752423",
    "companyId": null,
    "cityId": 66,
    "address": "test",
    "postalCode": "485484",
    "updatedAt": "1399/12/10 - 09:51",
    "createdAt": "1399/12/10 - 09:51"
  },
  {
    "id": "100161450588776282",
    "personId": "1001614505887752423",
    "companyId": null,
    "cityId": 45,
    "address": "test",
    "postalCode": "48548",
    "updatedAt": "1399/12/10 - 09:51",
    "createdAt": "1399/12/10 - 09:51"
  }
]

}

我的人 Class 对象数组为 属性:

 export class Person {
   id: string;
   name: string;
   type: number;
   addresses: Array<Address>;

   createdAt: string;
   updatedAt: string;
  }


export class Address{
id: string;
address: string;
postalCode: string;
cityId: number;
createdAt: string;
updatedAt: string;
}

所有 prop 都已填写,但 Address[] 未填写, 我这样调用 httpclient:

   this.http.get<Person>(url).subscribe(x => this.model = x);

我会提出两个解决方案

1- 如果您不打算创建 class 方法,您可以只使用一个接口。所以你的代码变成这样:

export interface Person {
    id: string;
    name: string;
    type: number;
    addresses: Address[];
    createdAt: string;
    updatedAt: string;
}

export interface Address {
    id: string;
    address: string;
    postalCode: string;
    cityId: number;
    createdAt: string;
    updatedAt: string;
}

2- 如果你真的需要使用类,那么你需要初始化你的 class 因为你现在正在做的不是。新代码:

export class Person {
    id: string;
    name: string;
    type: number;
    addresses: Address[];
    createdAt: string;
    updatedAt: string;

    constructor(personObject: any) {
        this.id = personObject.id;
        this.name = personObject.name;
        this.type = personObject.type;
        this.createdAt = personObject.createdAt;
        this.updatedAt = personObject.updatedAt;
        this.addresses = personObject.addresses.map((a: any) => new Address(a));
    }
}

export class Address {
    id: string;
    address: string;
    postalCode: string;
    cityId: number;
    createdAt: string;
    updatedAt: string;

    constructor(addressObject: any) {
        this.id = addressObject.id;
        this.address = addressObject.address;
        this.postalCode = addressObject.postalCode;
        this.cityId = addressObject.cityId;
        this.createdAt = addressObject.createdAt;
        this.updatedAt = addressObject.updatedAt;
    }
}

那么您的 api 请求:

 this.http.get<Person>(url).subscribe(x => this.model = new Person(x));