我是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);
});