我正在嘗試通過 api 獲取資料。
api客戶端:
export interface apiRequest {
locations: LocationOptions[];
}
interface FOLocations {
locationId: number;
}
interface LocationResult {
location: FOLocations[];
cityName: string;
}
export const locationCheck = async (
apiKey: string,
payload: apiRequest
): Promise<LocationResult[]> => {
let response = await axios.post<LocationResult[]>(
`api...`,
payload
);
return response.data;
運行代碼:
const locationPayload : apiRequest = {
locations:[{ cityName: "London"},{cityName: "New York"},{cityName: "Paris"}],
};
const locationResponse = await locationCheck(apiKey,locationPayload);
const [locationResponseRes] = locationResponse;
console.log(locationResponseRes);
實際輸出:
{
"location": {
"locationId": 1,
"cityName: "London",
}
}
預期輸出(我在 Postman 中得到的):
[
{
"location": {
"locationId": 1,
"cityName: "London",
}
},
{
"location": {
"locationId": 2,
"cityName": "New York",
},
},
]
因此,如您所見,并非所有資料都顯示在陣列中。也許我需要通過 entity[] 來完成?
uj5u.com熱心網友回復:
解構賦值語法是一種 JavaScript 運算式,可以將陣列中的值或物件中的屬性解包為不同的變數。所以不要從陣列中解壓第一個物件,只需回傳陣列本身。
我添加了一個小例子讓你更好地理解解構是如何作業的:
[a, b] = [10, 20];
console.log(a); // 10
[first, second] = [10, 20, 30, 40, 50];
console.log(second); // 20
[first, second, ...rest] = [10, 20, 30, 40, 50];
console.log(rest); // [30, 40, 50]
底線,回傳locationResponse而不是locationResponseRes物件(該線可以洗掉)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/365192.html
標籤:javascript 数组 打字稿 邮差
