打字稿:从复杂的有效载荷中提取多个数组

Typesctript: Extracting multiple arrays from complex payload

我是 Typescript 的新手,但似乎从 json 有效载荷中获取多个数组应该比我想象的要容易得多。什么是正确的方法?谢谢迈克。

我想从这段代码中提取 Customerrecords 到各自的数组


 this.httpReturn = this.http.post<any>('http://localhost:8400/DynAPI/web/Qry/CustomersQry', 
                                        PostData,  
                                        { headers: requestHeaders, observe: "response"}
                                        ).subscribe ((resp: HttpResponse<any>) => {   

resp.body:

{
  "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" 字段添加到请求中。

您可以先为负载创建接口或 class 定义。下面的界面示例基于您发布的 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);
});