【问题标题】:Writing common alert service using ionic2/angular2使用 ionic2/angular2 编写通用警报服务
【发布时间】:2016-08-31 13:32:30
【问题描述】:

我想在每个页面中显示警报消息。如何使用 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();
  }
}

【问题讨论】:

    标签: angular typescript ionic2


    【解决方案1】:

    由于Alerts 与视图相关而不与应用程序数据 相关,我认为我们可以使用@987654322 而不是使用服务 来执行此操作@。我们的想法是将该代码添加到您的 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');
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-06-08
      • 2016-10-20
      • 2012-06-04
      • 1970-01-01
      • 1970-01-01
      • 2017-04-08
      • 1970-01-01
      相关资源
      最近更新 更多