Ionic – parse JSON content and display it in a modal controller

Issue

I work on Ionic and I’d like to display the content of a JSON parsing (URL) in a modal component. I managed to get the content of the JSON query but when I try to insert it into the modal, it returns undefined.

Here is the snippet :

async openModal() {
  this.http.get(URL).subscribe(
    (data) > {
      var URLparsed  data['features'][0]['properties']['nom_dep'];
      console.log(URLparsed); // returns the content, that's ok
      this.URLparsed2  URLparsed;
    },
    (error) > {
      console.log(error);
    },
  );

  console.log('verif : ' + this.URLparsed2); // returns undefined

  const modal2  await this.modalCtrl.create({
    component: Modal2Page,
    cssClass: 'my-custom-class',
    componentProps: {
      URL: this.URLparsed2,
    },
  });

  return await modal2.present();
}

I must admin I’m stuck at this step. Have you got any ideas ?
Any help would be very appreciated.
Thanks !

Solution

The HTTP.get is asynchronous.

console.log(URLparsed); // returns the content, that's ok is call after console.log("verif : " + this.URLparsed2); // returns undefined

You can transform the RxJs Observable returned by the get() method to a Promise and then wait for this promise to resolved.

async openModal() {
    let data  await this.http.get(URL).toPromise();

    var URLparsed  (data['features'][0]['properties']['nom_dep']);
    console.log(URLparsed); // returns the content, that's ok
    this.URLparsed2  URLparsed;

    console.log("verif : " + this.URLparsed2);

    const modal2  await this.modalCtrl.create({
        component: Modal2Page,
        cssClass: 'my-custom-class',
        componentProps: {
            'URL': this.URLparsed2, 
        }
    });

    return await modal2.present(); 
}

This code is an example and is not tested.

Answered By – Marco

Leave a Comment