You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular:基于含父对象的HTTP响应数组实例化类对象

解决方案

修改你的fetchBookingInteractions方法,先从HTTP响应中提取外层的data数组,再进行类实例化,代码如下:

fetchBookingInteractions(bookingId: number): Observable<BookingInteractionsResponseModel[]> {
  // 定义匹配API响应结构的临时类型,替代接口实现类型约束
  type ApiResponse = { 
    data: Array<{
      id: number;
      bookingId: number;
      interactionType: number;
      interactionTypeDescription: string;
      interactionDateTime: string;
      userId: number;
    }> 
  };

  return this.httpClient.get<ApiResponse>(url)
    .pipe(
      map(response => {
        // 先取出响应中的data数组,再逐个实例化类
        return response.data.map(interaction => 
          new BookingInteractionsResponseModel(
            interaction.id,
            interaction.bookingId,
            interaction.interactionType,
            interaction.interactionTypeDescription,
            interaction.interactionDateTime,
            interaction.userId
          )
        );
      })
    );
}

关键调整说明

  1. 修正HTTP请求的泛型类型:
    原来的代码直接将get的泛型设为BookingInteractionsResponseModel[],但API响应是包含data字段的对象,类型不匹配。这里用ApiResponse类型别名描述响应结构,既满足类型检查,又不用定义接口。

  2. 先提取data数组再处理:
    在第一个map操作中,先从响应对象获取response.data,再对这个数组执行你之前写的实例化逻辑,和无外层data时的处理逻辑完全兼容。

  3. 可选优化:
    如果不想用类型别名,也可以临时用any跳过类型检查,但保留类型别名能避免后续修改时出现类型错误,更推荐前者。

另外注意:你的BookingInteractionsResponseModel类中定义了interactionText字段,但构造函数和API响应里都没有用到这个字段,属于冗余定义,建议清理或者补充对应逻辑。

内容的提问来源于stack exchange,提问作者whyshaiwhy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.23 18:12:44