首页 > 解决方案 > 定义 json 对象响应的接口

问题描述

我的 API 返回以下 JSOn 响应:

{
  key1: [
    name: "bob",
    gender: "male",
    children: [
      {
        name: "tom",
        gender: "male"
      },
      {
        name: "charley",
        gender: "male"
      }
    ]
  ],
  key2: {
    bob: 45,
    tom: 15,
    charley: 10
  }
}

我在我的 component.ts 中为响应声明了“任何”类型:

export class personComponent implements OnInit {
   personData: any[];
}

this._personService.getPersonData().subscribe(personData = > {
   this.data = personData;
}, error => this.errorMessage = <any>error, () => {
   this.personObject = this.data.key1; // Here it throws error - 'key1' doesnt exists on type any[];
})

我知道为对象和数组创建接口的方法。但是我如何为 JSON 输出创建接口。

任何人都可以在这里帮助我。

标签: angularangular5

解决方案


在您的模块中导入 HttpClientModule 而不是旧的 HttpModule。

import { HttpClientModule } from '@angular/common/http';

@NgModule({
  imports: [ HttpClientModule ]
})
[...]

你的输出看起来有点奇怪。一个界面可能看起来像:

export interface PersonData {
  [key: string]: {
    name?: string;
    gender?: string;
    children?: Array<{name: string, gender: string}>
    [key: string]: any; // optional
  }
}

然后在您的服务中使用提供一种类型解析器的 HttpClient

import { HttpClient } from '@angular/common/http';
[...]
constructor(private http: HttpClient) {}

getPersonData(): Observable<PersonData> {
  return this.http.get<PersonData>(url);
}

推荐阅读