Ad

How To Show A PresentAlert Inside A Method Then On Ionic 4?

- 1 answer

I'm trying to show a presentAlert inside a "then method", adding a document on a collection (Firebase + Ionic 4, if its successful, it should appear the alert). But the problem is I cannot reach the presentAlert method if i'm calling from inside the then method.

  addObject() {
this.afs.collection("Objects").add(this.object)
  .then(function () {
    console.log("Object successfully written!");
    this.presentAlert() //Doesn't work
  })
  .catch(function (error) {
    console.error(error);
  }); 
 }

  async presentAlert() {
    const alert = await this.alertController.create({
      header: 'Thank you!',
      message: 'This Object has been uploaded succesfully :)',
      buttons: ['OK']
    });
    await alert.present();
  }
Ad

Answer

Change the following:

  .then(function () {
    console.log("Object successfully written!");
    this.presentAlert() //Doesn't work
  })
  .catch(function (error) {
    console.error(error);
  }); 
 }

into this:

.then(() => {
    console.log("Object successfully written!");
    this.presentAlert() //Doesn't work
  })
  .catch((error) => {
    console.error(error);
  }); 
 }
Ad
source: stackoverflow.com
Ad