【问题标题】:check network status using network native使用网络本机检查网络状态
【发布时间】:2019-07-02 22:54:43
【问题描述】:

我正在从事 ionic 4 项目。我的项目正在从 url 获取数据 json 。我尝试使用Network native 进行离子检查我的应用程序的互联网连接。但我没有什么可显示的。没有数据,也没有要显示的警报。

 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();

     }

【问题讨论】:

  • 你链接了文档,你关注了吗?您似乎没有在任何地方订阅连接? it doesn't work 也没有告诉我们任何事情。您是否收到错误消息或其他信息?
  • 没有什么可显示的! .也许我以错误的方式编写了代码! .你有其他选择吗?
  • 你是按照文档说的那样做的吗?我不知道你期望this.network.onConnectthis.network.onDisconnect 应该做什么?
  • 我关注文档。我有很多错误
  • 好吧,您显示的这段代码根本不是文档所说的。那么,如果您按照文档中的方式进行操作,您会得到什么错误? :)

标签: angular ionic4


【解决方案1】:

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

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,他将努力检测到这一点,如果您打开 wifi 或移动数据,onConnect 同样工作。

如果您想在应用首次运行时检测到您的连接,您可以使用network.type

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


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

      this.getData()
    }

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

【讨论】:

  • 我也在我的回答中写了这个,如果您最初想要检查连接,请使用this.network.type !== 'none'(连接存在);)
  • 你对这个问题有什么想法吗? stackoverflow.com/questions/54592495/…
  • 最佳答案,在ionic5上对我来说很好。很好的解决方案
【解决方案2】:

将您的警报控制器代码移至其自己的异步函数,因为您不能在没有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'(连接存在)

【讨论】:

  • [ts] Cannot find name 'openAlert'. [2304]
  • 那么您是否已将函数openAlert 添加到您的代码中?你把它放在哪里了?
  • 天哪,没什么可显示的。甚至没有要显示的数据
  • 已编辑答案以使其尽可能清晰......应该可以。如果没有,请发布错误消息。
  • 你也立即取消订阅网络连接手表,为什么?当组件被销毁时,你应该取消订阅。
【解决方案3】:

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

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-11-05
    • 2010-09-23
    • 1970-01-01
    • 1970-01-01
    • 2019-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多