如何使用 Angular 中的 http 客户端和 Observables 遍历 JSON 对象数组

How to loop through an array of JSON objects using the http client and Observables in Angular

我有以下 url https://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/all_day.geojson 并且我想从 Angular.

中的服务发出 http 请求

数据是一个包含特征数组的对象。 在功能中,有 4 个对象 - 类型、属性、几何形状和 ID。 我想将 propertiesgeometry 对象存储在我的应用程序中它们自己的数组中。

我该怎么做?

我在 service.ts 中的代码是:

 public getEarthquakeData(): Observable<any[]> {
    return this.httpClient.get<any[]>(this.url);
  }

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

如有任何帮助,我们将不胜感激。

尝试:

import { map } from 'rxjs/operators';
.......
properties: Array<any>;
geometries: Array<any>;

ngOnInit() {
  this.earthquakeService.getEarthquakeData().pipe(
    // pluck the features array from the object
    map(data => data.features),
  ).subscribe(features => {
   // this will give you the array of objects you would like
   this.properties = features.map(feature => feature.properties);
   this.geometries = features.map(feature => feature.geometry);
 });
}

您发布的 url 的回复如下所示:

{
  "type": "",
  "metadata": [],
  "features": [
    {
      "type": "",
      "properties": {},
      "geometry": {},
      "id": ""
    }
  ],
  "bbox": []
}

您有兴趣提取一个 properties 的数组和一个 geometry 的数组。如果您想共享此功能,在您的服务中执行此操作很有意义。

为此,您需要在管道中的 RxJS map 运算符中转换响应。

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": []
}

component.ts

properties: [];
geometries: [];

ngOnInit() {
  this.earthquakeService.getEarthquakeData().subscribe(data => {    
   this.properties = data.properties;
   this.geometries = data.geometries;
 });
}

这是我整理的关于如何处理这个问题的快速堆栈闪电战。如果您不想使用服务来存储您的数据,只需在订阅之前将 http 调用上的管道移动到您的组件,然后将点击更改为映射。

也就是说,我强烈建议您将结果存储在服务中并使用路由解析器来触发数据获取,然后您可以在实际组件中使用数据订阅。

https://stackblitz.com/edit/angular-ccqrju

如果您想以其他方式存储和使用原始数据,这里的服务路由还会保留原始数据。