Ionic 2-警报对话框,带有不同组件上的按钮处理程序

San*_*kar 3 alert ionic-framework ionic2

我有ionic2应用程序,我想使用常见的警报控制器.所以我可以通过方法参数传输所有数据.在每个组件屏幕上,应单独处理"警告"对话框按钮.如何编写此类警报,以便根据需要处理单独组件上的按钮.请帮助我是Ionic2的新手.谢谢你.

Swa*_*twa 12

这是Alert的共享提供者

Shared.provider.ts

import { Injectable } from '@angular/core';
import { AlertController } from 'ionic-angular';

@Injectable()
export class SharedProvider { 
  constructor(private _alert: AlertController) { }
  public Alert = {
    confirm: (msg?, title?) => {
      return new Promise((resolve, reject) => {
        let alert = this._alert.create({
          title: title || 'Confirm',
          message: msg || 'Do you want continue?',
          buttons: [
            {
              text: 'Cancel',
              role: 'cancel',
              handler: () => {
                reject(false);
              }
            },
            {
              text: 'Ok',
              handler: () => {
                resolve(true);
              }
            }
          ]
        });
        alert.present();
      });

    },
    alert: (msg, title?) => {
      let alert = this._alert.create({
        title: title || 'Alert',
        subTitle: msg,
        buttons: ['Dismiss']
      });

      alert.present();
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

用法

Home.ts

import { SharedProvider } from '../../providers/shared.provider';

@Component({
    selector: 'page-home',
    templateUrl: 'home.html',
    providers: [SharedProvider]
})
export class HomePage {
    constructor(public shared: SharedProvider) {}

    deletePost(gossip) {
        this.shared.Alert.confirm().then((res) => {
            console.log('confirmed');
        }, err => {
            console.log('user cancelled');
        })
    }
}
Run Code Online (Sandbox Code Playgroud)

您可以添加更多常用功能.喜欢toast msg add-

 public Toast = {
    show: (text: string, duration?, position?, closeButton?, btnText?) => {
      this._toastMsg = this._toastCtrl.create({
        message: text,
        duration: duration || closeButton ? null : 3000,
        position: position || 'top',
        showCloseButton: closeButton || false,
        closeButtonText: btnText || 'OK'
      });
      this._toastMsg.present();
    },
    hide() {
      this._toastMsg.dismiss();
    }
  }
Run Code Online (Sandbox Code Playgroud)

现在显示吐司像this.shared.Toast.show('message');.同样,您可以在此处添加Storage,Loader和其他常用功能.