取消旧警报并显示最新警报-Ionic3

Moh*_*har 1 cordova typescript ionic2 ionic3 angular

我正在使用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();
});
Run Code Online (Sandbox Code Playgroud)

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

必需的行为:如果用户多次断开连接并重新连接,则对于网络变化的每个实例,都应显示一个警报,而较旧的警报将自动被关闭,因此在任何给定的时间点,不会向用户显示多个警报视图上任何警报的实例。

Moh*_*opi 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();
    });
Run Code Online (Sandbox Code Playgroud)