首页 > 解决方案 > Ionic 4 - AlertController:属性“当前”不存在 - Angular?

问题描述

我在 Ionic 4 中设置了一个新警报 - 空白类型:角度项目。这是基本警报,但我的项目运行时出现错误。

错误

“Promise”类型上不存在属性“present”。您是否忘记使用“等待”?

我创建与文档中相同的代码。链接:https ://ionicframework.com/docs/api/components/alert/AlertController/

我的代码:

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 功能..

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

标签: ionic-frameworkmobile-applicationionic-nativeionic4

解决方案


您正在使用的文档是指ionic 3 As you are using Ionic 4 , you need to refer to the current Ionic 4 docs and this

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

根据错误指定返回对象的承诺。

您的代码必须是:

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

推荐阅读