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

Angular组件中读取Object类型响应报错问题求助

问题解决方法

核心问题

你在组件中将data声明为userDetailsWithAddresses[](数组类型),但实际服务返回的是单个userDetailsWithAddresses对象,类型不匹配导致了报错和异常输出:

  • 访问this.data.user报错,因为数组类型没有user属性
  • 打印this.data[0]显示undefined,因为data根本不是数组,自然没有索引0的元素

修复步骤

  1. 修正组件中data的类型声明
    将数组类型改为单个对象类型:

    export class userComponent implements OnInit {
      // 移除数组类型标记[]
      data: userDetailsWithAddresses = null;
    
      getArchiveUserDetails(id: string){
        this.userService.getUserListWithAddressById(id).subscribe(response => {
          console.log(response);
          this.data = response;
          // 现在可直接访问对象属性
          console.log(this.data.user);
          console.log(this.data.addresses);
        });
      }
    }
    
  2. 验证服务接口返回结构
    确认后端接口返回的是单个userDetailsWithAddresses对象(而非数组)。如果后续接口需要返回数组,再将组件类型改回数组,并通过索引(如this.data[0].user)访问元素属性。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.16 04:40:54