如何将嵌套的json对象映射到angular 11中的模型?
我想用嵌套对象填充Person类 我的api回应是:如何将嵌套的json对象映射到angular 11中的模型?,angular,typescript,observable,httpclient,Angular,Typescript,Observable,Httpclient,我想用嵌套对象填充Person类 我的api回应是: { "id": "1001614505887752423", "type": 1, "name": "test contact", "createdAt": "1399/12/10 - 09:51", "updatedAt": "1399/12/10 - 09:51"
{
"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"
}
]
}
以及我的Person类,其中包含一个对象数组作为属性:
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;
}
导出类人员{
id:字符串;
名称:字符串;
类型:数字;
地址:数组;
createdAt:string;
updatedAt:string;
}
导出类地址{
id:字符串;
地址:字符串;
后代码:字符串;
cityId:编号;
createdAt:string;
updatedAt:string;
}
所有道具已填写,但地址[]未填写,
我这样称呼httpclient:
this.http.get<Person>(url).subscribe(x => this.model = x);
this.http.get(url.subscribe)(x=>this.model=x);
我建议两种解决方案
1-如果您不打算创建类方法,您可以使用接口。因此,您的代码如下所示:
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-如果你真的需要使用CLASES,那么你需要初始化你的类,因为你现在正在做的不是。新代码:
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));
this.http.get(url.subscribe(x=>this.model=newperson(x));
你解决了很多我的问题,但我在这行的构造函数中遇到了一个新问题:this.FormGroup=this.fb.FormGroup(Person,this.model);感谢使用带问号的构造函数参数,并解决了表单生成器错误