首页 > 解决方案 > 如何使用 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);
  }

我知道如何从我的组件调用此服务,但我不确定如何循环/访问我要保存的数据。

任何帮助将不胜感激。

标签: jsonangularrxjsobservableangular-httpclient

解决方案


您发布的网址的响应如下所示:

{
  "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;
 });
}

推荐阅读