Is it possible to make global service for Alert?


#1

I tried

import { Injectable } from '@angular/core';
import { NavController, Alert, App } from 'ionic-angular';

@Injectable()
export class MyAlert {
    private nav: NavController;
    constructor(private app: App) {
        this.nav = app.getActiveNav();
    }

    myAlert(title: string, text: string) {
        let alert = Alert.create({
            title: title,
            subTitle: text,
            buttons: ['OK']
        });
        this.nav.present(alert);
    }
}

On pages it throws exception:

Can't resolve all parameters for NavController: (?, ?, ?, ?, ?, ?, ?, ?).

#2

If I’m not wrong, you should declare the controller inside the constructor:

constructor(private app: App, private nav: NavController) {
    this.nav = app.getActiveNav();
}

#3

Unfortunately the same effect


#4

Using Ionic 2 RC4:

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

@Injectable()
export class ServiceAlert {

  constructor(public alertCtrl: AlertController) {}

  myAlertMethod(title: string, message: string) {
    let confirm = this.alertCtrl.create({
      title: title,
      message: message,
      enableBackdropDismiss: false,
      buttons: [
        {
          text: "OK",
          handler: () => {
            console.log('OK clicked');
          }
        }
      ]
    });
    confirm.present();
  }
}

#5

How would you add methods for the handler?


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

@Injectable()
export class ServiceAlert {

  constructor(public alertCtrl: AlertController) {}

  myAlertMethod(title: string, message: string, handler: any) {
    let confirm = this.alertCtrl.create({
      title: title,
      message: message,
      enableBackdropDismiss: false,
      buttons: [
        {
          text: "OK",
          handler: handler
        }
      ]
    });
    confirm.present();
  }
}