【问题标题】:Mapping an Angular HTTP Response properly正确映射 Angular HTTP 响应
【发布时间】:2022-01-21 00:54:37
【问题描述】:

我正在编写一个简单的 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 中的数组。如何正确映射响应以使数组不嵌套?

【问题讨论】:

    标签: angular angular-http


    【解决方案1】:

    您可以使用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 =&gt; response.data.items) 也可以,但解构有助于减少需要遍历的属性数量。

    【讨论】:

    • 这正是我需要的,谢谢!
    【解决方案2】:

    最简单的方法是创建一个复制内容结构的模型(类/接口)。对于这样的数据结构: {“数据”:{“数据”:{“项目”:[...]}}} 创建一个类(或接口),如下所示:

    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() { }
    }
    

    【讨论】:

      猜你喜欢
      • 2020-02-05
      • 1970-01-01
      • 1970-01-01
      • 2017-08-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多