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
相关产品推荐
相关产品推荐

