Search code examples
jsonangularrxjsobservableangular-httpclient

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


I have the following url https://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/all_day.geojson and i want to make a http request from a service in Angular.

The data is an Object which has an array of Features. In Features, there are 4 Objects- type, properties, geometry & id. I would like to store the properties and geometry objects in their own array inside my application.

How can I do this?

The code i have in my service.ts is :

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

I know how to call this service from my component but I am not sure how to loop through / access the data I want to save.

Any help would be greatly appreciated.


Solution

  • The response of the url you posted looks like this:

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

    You are interested in extracting an array of properties and an array of geometry. It makes sense to do this in your service if you want to share this functionality.

    To do that, you will need to transform the response in an RxJS map operator in the pipe.

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

    Then when you subscribe to this function in your component, you will receive an object that looks like:

    {
      "properties": [],
      "geometries": []
    }
    

    component.ts

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