使用 ionic2/angular2 编写通用警报服务

Writing common alert service using ionic2/angular2

我想在每个页面中显示警报消息。如何使用 angular2/ionic2 编写通用服务来实现此目的?

现在我正在按以下方式在每个“.ts”文件中编写 showAlert() 函数。

import { AlertController } from 'ionic-angular';

export class MyPage {
  constructor(public alertCtrl: AlertController) {
  }

  showAlert() {
    let alert = this.alertCtrl.create({
      title: 'New Friend!',
      subTitle: 'Your friend, Obi wan Kenobi, just accepted your friend request!',
      buttons: ['OK']
    });
    alert.present();
  }
}

由于 Alerts 与视图相关,而不是与 应用程序数据 相关,我认为与其使用 服务 为此,我们可以使用 Events。我们的想法是将该代码添加到您的 app.ts 文件中,如下所示:

constructor(public events: Events, private alertCtrl: AlertController, ...) {

    // Your code...

    // Subscribe to the event 'alert:presented'
    events.subscribe('alert:presented', (alertData) => {
      this.showAlert(alertData[0]);
    });  
}

// This method will show the alerts with the name sent as parameter
public showAlert(name: string) {
  let alert = this.alertCtrl.create({
      title: 'New Friend!',
      subTitle: 'Your friend, ' + name + ', just accepted your friend request!',
      buttons: ['OK']
  });
  alert.present();
}

然后,您可以从任何其他视图显示警报,只需执行以下操作

constructor(public events: Events, ...) { 

}

public yourMethod() {
  this.events.publish('alert:presented', 'Obi wan Kenobi');
}