Alert missing present

I’m in the process of learning new skills with Ionic 4 and Angular. I’m following a course on UDemy. In my first attempt to complete an assignment I could not get a simple example with AlertController to work. The code from UDemy looks like this (note: It’s a course from 2015 using Ionic 2):

showAlert()
{
let alert = this.alertController.create({
message: “Joepie”,
subHeader: “Test”
});
alert.present();
}

I’m using Visual Studio Code and it immediately gives me an error on ‘present’. After struggling a while with the code I came up with the code below. It is working (with Ionic 4) but I’m a bit uncertain about it. Is this how it is supposed to work?

showAlert()
{
let alert = this.alertController.create({
message: “Joepie”,
subHeader: “Test”
});
alert.then(x => x.present());
}

Hi Paul!

Some things have changed in Ionic 4 since Ionic 2 :wink: One of them being that when components get created with their controllers – like alertController.create(...) – they now return a promise containing the component instead of the component itself.

The code you wrote is correct, but you might find it easier to handle using async/await like this (the code is equivalent):

async showAlert() {
  const alert = await this.alertController.create({
    message: “Joepie”,
    subHeader: “Test”
  });

  await alert.present();
}

You can find the docs for Ionic 4 here: https://beta.ionicframework.com/docs/api/alert

Best,
Rodrigo

Ah, await, looks like C# :grinning: Yup, seems to work. Thanks for this.

Yeap, it’s just modern Javascript (ES2017), but it’s easier to reason about promises and resolved values. I’m glad it helped!