1

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 !

1
  • Please indent correctly your code to be easier to read.
    – Marco
    Dec 16, 2020 at 12:35

1 Answer 1

1

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.

1
  • I tested your code and that's exactly what I needed ! Thank you very much @Marco !!
    – Julien
    Dec 17, 2020 at 10:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.