在 ionic 5 中创建通用的可重用警报

create common reusable alert in ionic5

我是 ionic 的新手,我想创建一个自定义警告框,并想在每个页面中使用不同的 header 和消息。我想为它创建单独的组件并想传递 header 和消息值。 你能告诉我正确的做法是什么吗?

这是我的代码:

async presentAlertConfirm() {
    const alert = await this.alertController.create({
      cssClass: 'alertCustomCss',
      header: 'Confirm Action',
      message: 'Are you sure you want to delete this <div><img src = "./assets/icon/alert-circle-outline.svg" width="35px" height="35px"></div>',
      buttons: [
        {
          text: 'No',
          role: 'cancel',
          cssClass: 'cancel-btn',
          handler: (blah) => {
            console.log('Confirm Cancel);
          }
        }, {
          text: 'Yes',
          cssClass: 'ok-btn',
          handler: () => {
            console.log('Confirm Okay');
          }
        }
      ]
    });

    await alert.present();
  }

我想将此代码放在单独的组件中并使其可重用。

您可以为此使用服务。

像这样将警报功能添加到您的服务中

async presentAlertConfirm(header: string, massage: string) {
    const alert = await this.alertController.create({
      cssClass: 'alertCustomCss',
      header,
      massage,
      buttons: [
        {
          text: 'No',
          role: 'cancel',
          cssClass: 'cancel-btn',
          handler: (blah) => {
            console.log('Confirm Cancel');
          }
        }, {
          text: 'Yes',
          cssClass: 'ok-btn',
          handler: () => {
            console.log('Confirm Okay');
          }
        }
      ]
    });

    await alert.present();
    return alert;
  }

然后您可以在导入服务的任何地方使用此功能。 (我没有测试代码)