Alert component - native alert and ionic alert


#1

Hey,

I would like to create an alert component which displays a native alert on devices and ionic alert on browsers.
Do you guys have an idea how to do that?
The idea is to use it with promises.

Thanks

JB


#2

You could use condition and create alert by this. But why you need it? Why not use ionic alert?


#3

I would like to do that due to this issue https://github.com/driftyco/ionic/issues/6224 that won’t be fixed.

Here is the class I’d like to use:

import {NavController} from "ionic-angular/index";
import {Platform} from "ionic-angular/index";
import {Dialogs} from "ionic-native/dist/index";
import {Alert} from "ionic-angular/index";

export interface AlertOption {
  message: string;
  title?: string;
  buttonName?: string;
}

export class Alert {
  private _useNativeComponent:boolean = true;


  constructor(private nav:NavController, private platform:Platform) {
    this._useNativeComponent = platform.is('cordova');
  }

  /**
   *
   * @param option
   * @returns {Promise<any>}
   */
  create(option?:AlertOption):Promise<any> {

    option.title = option.title || 'Alert';
    option.buttonName = option.buttonName || 'OK';

    if (this._useNativeComponent) {
      return this.createNative(option.message, option.title, option.buttonName);
    }
    else {
      return this.createIonic(option.message, option.title, option.buttonName);
    }


  }

  private  createNative(message, title, buttonName):Promise<any> {
    return Dialogs.alert(message, title, buttonName);
  }

  private  createIonic(message, title, buttonName):Promise<any> {
    return new Promise<any>(resolve=> {
      let alert = Alert.create({
        title: title,
        message: message,
        buttons: [{
          text: buttonName,
          handler: data=> {
            resolve();
          }
        }]
      });

      this.nav.present(alert);
    });
  }
}

But I don’t know how to instantiate the class once and use it everywhere I want to, like the ionic’s Alert