json - 如何使用 Angular 中的 http 客户端和 Observables 遍历 JSON 对象数组
问题描述
我有以下网址https://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/all_day.geojson并且我想从 Angular 中的服务发出 http 请求。
数据是一个具有特征数组的对象。在功能中,有 4 个对象——类型、属性、几何和 id。我想将属性和几何对象存储在我的应用程序中自己的数组中。
我怎样才能做到这一点?
我在service.ts中的代码是:
public getEarthquakeData(): Observable<any[]> {
return this.httpClient.get<any[]>(this.url);
}
我知道如何从我的组件调用此服务,但我不确定如何循环/访问我要保存的数据。
任何帮助将不胜感激。
解决方案
您发布的网址的响应如下所示:
{
"type": "",
"metadata": [],
"features": [
{
"type": "",
"properties": {},
"geometry": {},
"id": ""
}
],
"bbox": []
}
您有兴趣提取 的数组properties
和 的数组geometry
。如果您想共享此功能,在您的服务中执行此操作是有意义的。
为此,您需要map
在管道中的 RxJS 运算符中转换响应。
public getEarthquakeData(): Observable<{ properties: [], geometries: []}> {
return this.httpClient.get<any>(this.url).pipe(
// this will run when the response comes back
map((response: any) => {
return {
properties: response.features.map(x => x.properties),
geometries: response.features.map(x => x.geometry)
};
})
);
}
然后,当您在组件中订阅此功能时,您将收到一个如下所示的对象:
{
"properties": [],
"geometries": []
}
组件.ts
properties: [];
geometries: [];
ngOnInit() {
this.earthquakeService.getEarthquakeData().subscribe(data => {
this.properties = data.properties;
this.geometries = data.geometries;
});
}
推荐阅读
- java - 在选项卡式活动中打开新片段时播放声音
- javascript - Node.js 可以在不同的页面上触发点击事件吗?
- c# - C# 检查一个列表
在列表框中选择项目,如果是,则返回 true - python - 在 Raspberry Pi 上导入熊猫时出错
- python - 从 Python 上的多个文件创建加密的 Zip 文件
- javascript - reduce() 方法从对象数组返回 NaN
- ios - Swift 发送请求失败,但 Postman 成功
- php - PHP MySQL:如何从图像表中检索与项目 ID 关联的所有图像
- clang++ - clang++-5.0 找不到头文件
- swift - 如何在 Swift / MacOS 中将菜单项添加到顶部导航栏