Search code examples
jsonangularhttpclientionic4

best way to store and process JSON data from httpClient get request in Angular


I am new to Angular, and I'm working on a project with Ionic Angular. My goal is to use the httpClient and send get request to a Country api that will send me back a JSON of all the countries. The way I used to store the data is to create an interface matching the data type that I am receiving from and then subscribe to that observable and store the data into the array of the data type that I defined.

But for the countries, the only thing I need is the name, is it possible to store the name of each countries into an array without defining the structure of the receiving JSON object, because it's very long and complex.

This is the code that I am trying to do:

Getting the countries as Observable. in the Country.Service file

  getCountry(): Observable<any>{
    return this.http.get<any>(this.url2);
  }

Declaring variable and store the data of countries:

public countries: any;

  storeCountry(){
    this.countryService.getCountry().subscribe(
      data => {
        this.countries = data;
      }
    );

This is what I'm trying to do, but I was not able to get the data into the countries variable to access it as array, when I console log the countries it is showing as undefined.

What would be the best approach to what I'm trying to achieve? I would appreciate any help,


Solution

  • I assume the data you receive from the backend is of the structure

    countries = [
      { 'name': 'USA', 'id': '1', ... },
      { 'name': 'UK', 'id': '2', ... },
      ...
    ]
    

    In that case you could remove the <any> from the GET request and use map() method to obtain only the country names as an array. Try the following

    Service

    import { pipe } from 'rxjs';
    import { map } from 'rxjs/operators';
    
    getCountry(): Observable<any>{
      return this.http.get(this.url2).pipe(map(countries => countries.map(country => country.name);
    }
    

    Explanation

    If you're new to Rxjs as well, then you might be confused why there are two map functions.

    1. The pipe(map()) part belongs to Rxjs.

      • pipe() function can be used to modify and control the data flow using various Rxjs operators.
      • We use only one operator map() which projects a custom function on the source observable (JSON returned from the API) and returns the resulting value as an observable.
    2. We use the map() function in countries.map() to provide our custom projection function. It creates a new array based on our callback to use only the name property of the source object array.

    Then you could subscribe to it in the component

    storeCountry(){
      this.countryService.getCountry().subscribe(
        countries => {
          this.countries = countries; // this.countries = ['USA', 'UK', ...]
        },
        error => {
          // handle error
        }
      );
    }