使用网络本机检查网络状态

check network status using network native

我正在从事 ionic 4 项目。我的项目正在从 url 获取数据 json 。我正在尝试使用 Network native for ionic 来检查我的应用程序的互联网连接。但我没有显示任何内容。没有数据,也没有要显示的警报。

 constructor(private http: HTTP, public loadingController: LoadingController,private network: Network,
   public alertController : AlertController, public platform : Platform) {


    // watch network for a disconnection
    let disconnectSubscription = this.network.onDisconnect().subscribe(() => {

      this.AlertNet()

    });

    // stop disconnect watch
    disconnectSubscription.unsubscribe();


    // watch network for a connection
    let connectSubscription = this.network.onConnect().subscribe(() => {
      console.log('network connected!');


      this.getData()

      setTimeout(() => {
        if (this.network.type === 'wifi') {
          console.log('we got a wifi connection, woohoo!');
        }
      }, 3000);
    });

    // stop connect watch
    connectSubscription.unsubscribe();



       }

      async getData() {


          const loading = await this.loadingController.create({
            message: 'Loading'
          });
          await loading.present();
          this.http.get('/v1/airport.json?code=krt', {}, {})
          .then(data => {

            this.test = JSON.parse(data.data);
            const parsed = JSON.parse(data.data);


          }), err=>{
            this.test =err
            loading.dismiss()
          }



      }


     async AlertNet(){

      const alert = await this.alertController.create({
        header: 'Alert',
        subHeader: 'No internet',
        message: 'You do not have an Internet connection. Please check your connection status',
        buttons: [{
          text: "Ok",
          handler: () => { this.platform.backButton.subscribe(()=>{
            navigator['app'].exitApp();
        });
       }
        }]    
        });

      await alert.present();

     }

将您的警报控制器代码移到它自己的异步函数中,因为您不能在没有 async 的情况下使用 await,正如您已经确定的那样。另外,我建议将连接代码放在 platform.ready 中,以便我们确定它已加载:

constructor(private platform: Platform, private network: Network ......) {
  this.platform.ready().then(() => {
    let disconnectSubscription = this.network.onDisconnect().subscribe(() => {
      this.openAlert();
    });

  // watch network for a connection
  let connectSubscription = this.network.onConnect().subscribe(() => {
    console.log('network connected!');
    // We just got a connection but we need to wait briefly
    // before we determine the connection type. Might need to wait.
    // prior to doing any api requests as well.
    setTimeout(() => {
      if (this.network.type === 'wifi') {
        console.log('we got a wifi connection, woohoo!');
        this.getData();
      }
    }, 3000);
  });
  });
}

async openAlert() {
  const alert = await this.alertController.create({
    header: 'Alert',
    subHeader: 'No internet',
    message: 'You do not have an Internet connection.'
    buttons: [{
      text: "Ok",
      handler: () => { 
        // you are propbably going to run into issues here...
        this.platform.backButton.subscribe(() => {
          navigator['app'].exitApp();
        });
       }
      }]    
    });
  await alert.present();
}

这在测试时似乎工作得很好,在连接打开时启动应用程序,然后将其关闭,然后重新打开。

如果需要,在进入组件时,检查是否存在连接,然后检查 this.network.type !== 'none'(存在连接)

我终于找到问题所在了。几次失败的尝试得出了结论:

constructor(private http: HTTP, public loadingController: LoadingController,public network: Network,

   public alertController : AlertController, public toastController : ToastController) {


    if (this.network.type == 'none'){
      this.AlertNet()


    }else if(this.network.type === 'wifi'){

      this.getData()
    }

    this.network.onConnect().subscribe(()=> {
      if(network.Connection.WIFI){

        this.presentToastWithOptions()

      }
    });

    this.network.onDisconnect().subscribe(()=> {
      this.presentToast()
    });

   }
   async presentToast() {
    const toast = await this.toastController.create({
      message: 'You dont have internet connection :(',
      duration: 2000
    });
    toast.present();
  }

  async presentToastWithOptions() {
    const toast = await this.toastController.create({
      message: 'Internet connection is back :)',
      showCloseButton: true,
      position: 'top',
      closeButtonText: 'Done'
    });
    toast.present();
  }

 async AlertNet(){

  const alert = await this.alertController.create({
    header: 'Alert',
    subHeader: 'No internet',
    message: 'You do not have an Internet connection. Please check your connection status',
    buttons: [{
      text: "Ok"


    }]    
    });

  await alert.present();

 }

如果您使用 onConnectonDisconnect,它们仅适用于检测到的连接。例如,如果您在应用程序中并关闭 wifi onDisconnect 他将检测到这一点,并且 onConnect 如果您打开 wifi 或移动数据,他将同样工作。

如果您想为您的应用检测第一个 运行 的连接,您可以使用 network.type

   if (this.network.type == 'none'){
      this.AlertNet()


    }else if(this.network.type === 'wifi'){

      this.getData()
    }

当我使用上面的代码和 运行 应用程序时,他开始检查我的 phone 是否有互联网连接或网络。如果他没有,他会立即提醒我。

不要使用插件来检查网络,我有一个非常非常简单的方法来检查用户是否有互联网连接,所以我们所要做的就是使用这个:

if (navigator.onLine) {
   console.log('Internet is connected');
} else {
   console.log('No internet connection');
}

这里navigator不是我创建的变量。航海家。 onLine 属性 提供一个布尔值,无论用户是否连接到 Internet。 …浏览器和真实设备还支持浏览器离线或在线时的在线和离线事件。

这是非常简单有效的方法,我相信它会有所帮助。