关闭旧警报并显示最新警报 - Ionic3

时间:2017-08-28 12:34:20

标签: angular cordova typescript ionic2 ionic3

我正在使用Ionic 3的警报,我正面临着警报堆积的问题。 我正在使用网络插件检查用户是否连接到网络(WiFi / 2G / 3G等),并且每次用户下线或上线时都会触发警报。

this.connectSubscription = this.network.onConnect().subscribe(() => {
  console.log('network connected!');
  let connectedToInternet = this.alertController.create({
    subTitle: 'Connected to Internet',
    buttons: ['OK']
  });
  connectedToInternet.present();
});

this.disconnectSubscription = this.network.onDisconnect().subscribe(() => {
  let noInternetAlert = this.alertController.create({
    subTitle: 'No Internet Connection. Please enable Wifi or Mobile data to continue.',
    buttons: ['OK']
  });
  noInternetAlert.present();
});

当前行为:如果用户多次断开连接并重新连接,则对于网络中的每个更改实例,都会显示一条警报,警报将叠加在视图上,直到用户手动关闭警报为止

必需行为:如果用户多次断开连接并重新连接,则对于网络中的每个更改实例,应在旧警报自动被解除时显示警报,以便在任何给定时间点,用户不会在视图上显示任何警报的多个实例。

3 个答案:

答案 0 :(得分:5)

isAvailable: Boolean; //boolean variable helps to find which alert we should dissmiss   
connectedToInternet; //made global to get access 
noInternetAlert; // made global to get access


 this.connectSubscription = this.network.onConnect().subscribe(() => {
      console.log('network connected!');

      if(!this.isAvailable){ //checking if it is false then dismiss() the no internet alert
        this.noInternetAlert.dismiss();
      }
       this.isAvailable =true;

      this.connectedToInternet = this.alertController.create({
        subTitle: 'Connected to Internet',
        buttons: ['OK']
      });
      this.connectedToInternet.present();
    });

    this.disconnectSubscription = this.network.onDisconnect().subscribe(() => {

     if(this.isAvailable){// if it is true then dismiss the connected to internet alert
        this.connectedToInternet.dismiss();
      }
      this.isAvailable = false;
      this.noInternetAlert = this.alertController.create({
        subTitle: 'No Internet Connection. Please enable Wifi or Mobile data to continue.',
        buttons: ['OK']
      });
      this.noInternetAlert.present();
    });

答案 1 :(得分:3)

标记正确的答案解决了问题中提出的问题,但另外,还有一个更精细的解决方案,可以涵盖多个警报堆叠案例,我已成功实施。我使用提供程序为AlertController创建了一个包装器,该提供程序将维护每个警报的状态,然后关闭旧警报并显示新警报。下面的代码是针对提供者的,它基本上是我用于我在应用程序中创建的所有警报的包装类:

import {AlertController} from 'ionic-angular';
@Injectable()
export class AlertserviceProvider {
  alerts: any[] = [];

  constructor(public alertController: AlertController) {
  }

  newAlert(title, subTitle){
    let alert = this.alertController.create({
      title:title,
      subTitle:subTitle
    });
    this.alerts.push(alert);
    return alert;
  }

  dismissAlert(){
    if(this.alerts.length){
      this.alerts.forEach(element => {
        element.dismiss();
      });
    }
    this.alerts = [];
  }

}

可以使用以下代码在页面中使用它:

import { AlertserviceProvider } from '../../providers/alertservice/alertservice';
...
...
...

constructor(..,public alertHandler: AlertserviceProvider,..) {
...
}
testMethod(){
    //First we dismiss the previous alerts if any
    this.alertHandler.dismissAlert();
    //Creating the new alert
    var testAlert = this.alertHandler.newAlert('Title','SubTitle');
    //Adding buttons to the new alert
    testAlert.addButton({
        text: 'OK',
        role: 'OK',
        handler: () => {
          //Handler actions go here - include the Handler only if required
        }
      });
    testAlert.present();
}

不要忘记导入提供程序并在构造函数参数中为其创建变量。

如果您想添加多个按钮,CSS可能会搞砸。请查看此问题的答案:https://stackoverflow.com/a/39188966/4520756

请注意,要使此解决方案正常工作,只需使用此包装器创建所有警报。它不支持使用Ionic提供的默认AlertController创建的警报。希望这有助于任何希望避免堆叠警报的人!

有关较小案例的替代且更简单的解决方案,请查看以下答案:https://stackoverflow.com/a/39940803/4520756

致谢:https://stackoverflow.com/a/43318081/4520756

答案 2 :(得分:1)

我已经完成了如下所示。代码不言自明。如果您需要任何解释,请告诉我。

我创建了一个povider,如下所示。

网络state.ts

import { Injectable } from '@angular/core';
import { Network } from '@ionic-native/network';
import { ToastController } from "ionic-angular";
import { Subscription } from "rxjs/Subscription";

@Injectable()
export class NetworkStateProvider {

  public isInternetAvailable = true; private connectSubscription$: Subscription = null;

  constructor(private network: Network, private toastCtrl: ToastController) {
  }

  //Watch for internet connection
  public WatchConnection() {
    if (this.connectSubscription$) this.connectSubscription$.unsubscribe();
    this.connectSubscription$ = this.network.onDisconnect().subscribe(() => {
      this.isInternetAvailable = false;
      this.showToast('Internet connection unavailable');
      console.log(this.network.type, this.isInternetAvailable, 'No internet!');
      if (this.connectSubscription$) this.connectSubscription$.unsubscribe();
      this.connectSubscription$ = this.network.onConnect().subscribe(() => {
        console.log('Network connected!');
        setTimeout(() => {
          if (this.network.type === 'wifi' || this.network.type === '4g' || this.network.type === '3g' || this.network.type === '2g' || this.network.type === 'cellular' || this.network.type === 'none') {
            this.isInternetAvailable = true;
            this.showToast('Internet connection available');
            this.WatchConnection();
            console.log(this.network.type, this.isInternetAvailable, 'we got a connection!');
          }
        }, 3000);
      });
    });
  }

  //show Toast
  showToast(message, timeout = 3000) {
    let toast = this.toastCtrl.create({
      message: message,
      duration: timeout,
      position: 'bottom',
    });
    toast.present()
  }

  //check Internet Availability
  checkInternetAvailability(): boolean {
    if (!this.isInternetAvailable) {
      this.showToast('Internet connection unavailable');
       return false;
    } else if (!this.isInternetAvailable) {
      this.showToast('Internet connection unavailable');
      return false;
    } else {
      return true;
    }
  }
}

我在这里使用了provider

app.component.ts

constructor(private network: NetworkStateProvider,public platform: Platform){
 platform.ready().then(() => {
       this.network.WatchConnection();
    });
}