【问题标题】:How to loop through an array of JSON objects using the http client and Observables in Angular如何使用 Angular 中的 http 客户端和 Observables 遍历 JSON 对象数组
【发布时间】:2020-03-04 15:20:47
【问题描述】:

我有以下网址 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);
  }

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

任何帮助将不胜感激。

【问题讨论】:

  • 您要将数据存储在哪里?在服务中?
  • 您的预期输出的形状是什么?
  • @KurtHamilton 我想将数据存储在组件中。所以我知道我需要订阅组件。
  • @Reza 我不太确定。我想这就是为什么我有点困惑。也许最好将每个特征存储在一个数组中?但如果我这样做了,我怎么能访问 feature.properties 例如
  • @HiddenSquid 所以你想在你的组件中有geometries: Array&lt;Geometries&gt;properties: Array&lt;Properties&gt;。/service?

标签: json angular rxjs observable angular-httpclient


【解决方案1】:

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

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

组件.ts

properties: [];
geometries: [];

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

【讨论】:

  • 非常感谢!这就是我一直在寻找并按预期工作的东西。你能帮我解决另一个问题吗? QUESTION
【解决方案2】:

试试:

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

【讨论】:

    【解决方案3】:

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

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

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

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

    【讨论】:

      猜你喜欢
      • 2018-08-12
      • 2022-08-22
      • 2018-07-02
      • 2020-09-23
      • 1970-01-01
      • 2017-11-10
      • 2013-06-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多