angular - 定义 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 输出创建接口。
任何人都可以在这里帮助我。
解决方案
在您的模块中导入 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);
}
推荐阅读
- python - 根据发布请求删除数据库中的对象
- arrays - 使用 Swift 过滤嵌套数组
- javascript - 单击导航链接后无法关闭全屏菜单
- css - 当屏幕变小时,避免在带有图标的按钮中换行
- ios - 检索 UIActivityViewController 保存的图像路径
- notepad++ - 在 Notepad++ 中更改 URL/超链接的颜色?
- coq - 小于两个自然数之间的关系
- node.js - 如何在 type-graphql 中使用带整数的 simple-json
- python - PermissionError: [WinError 5] Access is denied - 在 vs 代码中运行程序
- php - 在 PHP 中将对象转换为数组