angular - Typesctript:从复杂的有效载荷中提取多个数组
问题描述
我是 Typescript 的新手,但似乎从 json 有效负载中获取多个数组应该比我想象的要容易得多。什么是正确的方法论?谢谢迈克。
从这段代码中,我想在各自的数组中提取客户和记录
this.httpReturn = this.http.post<any>('http://localhost:8400/DynAPI/web/Qry/CustomersQry',
PostData,
{ headers: requestHeaders, observe: "response"}
).subscribe ((resp: HttpResponse<any>) => {
响应体:
{
"RequestIO": {
"Customer": [
{
"ID": 37,
"Country": "Austria",
"Name": "Abc Mountain Bikes",
"Address": "Alttorstr. 23",
"City": "Salzburg",
"State": "West"
},
{
"ID": 1020,
"Country": "USA",
"Name": "Abc Sports II",
"Address": "3233 Pine St",
"City": "Newtown",
"State": "CA"
}
],
"Records": [
{
"Count": 2
}
]
}
}
解决方案
observe: "response"
如果您只对响应的正文感兴趣,则无需将字段添加到请求中。
您可以首先为有效负载创建接口或类定义。下面的接口示例基于您发布的 json,您可能希望也可能不希望更改名称以更好地满足您的需求。
export interface Customer {
ID: number;
Country: string;
Name: string;
Address: string;
City: string;
State: string;
}
export interface Record {
Count: number;
}
export interface RequestIO {
Customer: Customer[];
Records: Record[];
}
export interface CustomersQryResponse {
RequestIO: RequestIO;
}
然后所有数据绑定都应该根据您的请求自动进行。
this.http.post<CustomersQryResponse>(
'http://localhost:8400/DynAPI/web/Qry/CustomersQry',
PostData
).subscribe(resp => {
console.table(resp.RequestIO.Customer);
console.table(resp.RequestIO.Records);
});