You need to enable JavaScript to run this app. Angular调用API报错Property 'people' does not exist on type 'Object'如何解决?
优惠活动
大模型
产品
解决方案
定价
更多

Angular调用API报错Property 'people' does not exist on type 'Object'如何解决?

报错原因及解决方案

报错「Property 'people' does not exist on type 'Object'」属于TypeScript静态类型检查类错误。Angular的HttpClient.get方法默认返回值类型为Observable<Object>,TypeScript默认的Object类型上不存在预定义的people属性,因此编译阶段会直接抛出该错误,该报错和运行时API是否实际返回people字段无关。

推荐解决方案:指定请求泛型(保留完整类型校验能力)

这是最符合TypeScript开发规范的实现方式,先定义API返回结构的类型约束,再给http.get方法传入对应泛型即可,修改后的完整代码如下:

import { Component } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { UserModel } from './model/user.model';
import { Observable } from 'rxjs';

// 自定义API返回值的结构类型
interface ApiResponse {
  people: UserModel[]
}

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  users: UserModel[] = [];

  constructor(public http: HttpClient) {
    this.readAPI('https://**REMOVED FOR PRIVACY**/people')
      .subscribe((data) => {
        // 此时data已被自动识别为ApiResponse类型,可正常读取people属性
        this.users = data.people;
        console.log(data, data.people);
      });
  }

  readAPI(URL: string): Observable<ApiResponse> {
    // 给get方法传入泛型约束返回值结构
    return this.http.get<ApiResponse>(URL);
  }
}

临时调试方案:使用类型断言跳过校验

如果仅需要临时调试快速跳过类型检查,可直接将返回的data断言为任意类型:

.subscribe((data) => {
  this.users = (data as any).people;
  console.log(data, (data as any).people);
});

紧急兼容方案:关闭单文件类型校验(不推荐常规使用)

在当前ts文件的第一行添加注释// @ts-nocheck,可关闭整个文件的TypeScript类型校验,该方案会丢失TS的类型保护能力,仅建议紧急场景下临时使用。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.22 01:45:04