내 api 응답이 중첩 된 개체로 각도로 내 Person 클래스를 채우고 싶습니다.
{
"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;
}
모든 소품이 채워졌지만 Address []가 채워지지 않았습니다. httpclient를 다음과 같이 호출합니다.
this.http.get<Person>(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- 정말 clasess를 사용해야하므로 지금하고있는 일이 아니기 때문에 클래스를 초기화해야합니다. 새 코드 :
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));
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다