我正在撰寫一個簡單的 Angular 應用程式,它呼叫外部 API 獲取資料。其中一個 API 呼叫以這種方式回傳資料:
{
"data": {
"items": [
{
// An Appointment object is here
},
{
...
}
]
}
}
我有一個AppointmentService使用 Angular HTTP 庫呼叫 API 的工具:
getBookedAppointments(userID : number) : Observable<Appointment[]> {
return this.http.get<Appointment[]>('/api/url/goes/here')
.pipe(retry(2), catchError(this.handleError));
}
最后,我試圖將這些 Appointment 物件放入一個陣列中:
this.AppointmentService.getBookedAppointments(id).subscribe((appts : Appointment[]) => {
// appts contains {"data" : {"data": {"items" : [...]}}}
})
問題在于 API 回傳嵌套在 data.items 中的陣列。如何正確映射回應以使陣列不嵌套?
uj5u.com熱心網友回復:
您可以使用該map()運算子從 API 回應中回傳任何物件解構。您還應該讓您的 HTTP 回傳正確的型別。這是一個示例解決方案:
interface ApiResponse {
data: {
items: Appointment[];
}
}
getBookedAppointments(userID : number) : Observable<Appointment[]> {
return this.http.get<ApiResponse>('/api/url/goes/here')
.pipe(
map(({data}) => data.items)
retry(2),
catchError(this.handleError)
);
}
注意:我在map()運算子中使用物件解構。您也可以這樣做map(response => response.data.items),但解構有助于減少您需要遍歷的屬性數量。
uj5u.com熱心網友回復:
最簡單的方法是創建一個復制內容結構的模型(類/介面)。對于這樣的資料結構: {"data" : {"data": {"items" : [...]}}} 創建一個類(或介面),如下所示:
export class Response {
constructor() { }
public data: ResponseData = new ResponseData();
}
export class ResponseData {
public data: Item = new Item();
}
export class Item {
public items: Appointment[] = [];
}
export class Appointment {
constructor() { }
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/417398.html
標籤:
上一篇:將回圈中的每到2行合并為一個
下一篇:按姓氏字母排序
