Ionic 4 - AlertController: Property 'present' does not exist - Angular?

Simon picture Simon · Jan 16, 2019 · Viewed 24.3k times · Source

I'm setting up a new alert in Ionic 4 - blank type:angular project. It's basic alert but I get an error occured running of my project.

Error

Property 'present' does not exist on type 'Promise'. Did you forget to use 'await'?

My create the same code as in documentation. Links:https://ionicframework.com/docs/api/components/alert/AlertController/

My code:

import { AuthenticationService } from './../../services/authentication.service';
import { Component, OnInit } from '@angular/core';
import { AlertController, LoadingController, NavController } from 
'@ionic/angular';

@Component({
  selector: 'app-register',
  templateUrl: './register.page.html',
  styleUrls: ['./register.page.scss'],
})
export class RegisterPage implements OnInit {
  createSuccess = false;
  registerCredentials = { email: '', password: '' };

 constructor(
   private nav: NavController,
   private auth: AuthenticationService,
   private alertCtrl: AlertController) { }

 ngOnInit() {
 }

 presentAlert() {
    const alert = this.alertCtrl.create({
    message: 'Low battery',
    subHeader: '10% of battery remaining',
    buttons: ['Dismiss']
   });
   alert.present(); <--- error Property 'present' does not exist on type 'Promise<HTMLIonAlertElement>'. Did you forget to use 'await'?
}
public register() {
this.auth.register(this.registerCredentials).subscribe(success => {
  if (success) {
    this.createSuccess = true;
    this.showPopup('Success', 'Account created.');
  } else {
    this.showPopup('Error', 'Problem creating account.');
  }
},
  error => {
    this.showPopup('Error', error);
  });
}

showPopup function that shoulbe be working..

showPopup(title, text) {
let alert = this.alertCtrl.create({
  message: title,
  subHeader: text,
  buttons: [
    {
      text: 'OK'
    }
  ]
});
alert.present(); <-- the same error
}

Answer

Suraj Rao picture Suraj Rao · Jan 16, 2019

The documentation you are using refers to ionic 3 As you are using Ionic 4, you need to refer to the current Ionic 4 docs and this.

this.alertController.create({...})

returns promise of the object as the error specifies.

Your code needs to be:

 async presentAlert() {
    const alert = await this.alertCtrl.create({
    message: 'Low battery',
    subHeader: '10% of battery remaining',
    buttons: ['Dismiss']
   });
   await alert.present(); 
}