Angular - 错误 TS2339:“对象”类型上不存在属性“结果”

时间:2021-07-02 23:03:02

标签: angular

在 Angular-12 应用程序中,我有来自后端的这个 JSON api GET 请求响应:

{
  "message": "Company Detail.",
  "error": false,
  "code": 200,
  "results": {
     "countries": [
        {
            "name": "Spain",
            "id": 2
        },
        {
            "name": "Italy",
            "id": 1
        }
     ]
  }
}

然后我有这个组件来显示国家作为选择下拉:

countries!: any[];

this.api.get('countries/list', this.headers).subscribe(data => {
  this.countries = data.results.countries
});

我收到此错误:

<块引用>

错误 TS2339:类型“对象”上不存在属性“结果”

结果突出显示:

<块引用>

this.countries = data.results.countries

我该如何解决?

谢谢

1 个答案:

答案 0 :(得分:0)

您应该使用 {{1} 在组件(必须)和 API 服务(可选但推荐)中指定 data 响应的数据类型} 或 interface


解决方案

<块引用>

response.interface.ts

class
<块引用>

api.service.ts

export interface IResponse<T> {
  message: string;
  error: boolean;
  code: number;
  results: T;
}

export interface ICountries {
  countries: ICountry[];
}

export interface ICountry {
  name: string;
  id: number;
}
<块引用>

.component.ts

import { Observable } from 'rxjs';

export class ApiService {
  ...

  get(url: string, headers: HttpHeaders): Observable<any> {
    const requestOptions = {
      headers: headers
    };

    return this.http.get(this.apiUrl + url, requestOptions); 
  }
}

Sample solution on StackBlitz