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

时间:2019-02-08 16:43:39

标签: angular ionic4

我正在从事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();

     }

3 个答案:

答案 0 :(得分:1)

将警报控制器代码移至其自己的异步功能,因为如已建立,您不能在没有engine = create_engine('sqlite:///database.db', echo=True) Base = declarative_base(engine) class Kinases(Base): __tablename__ = 'Kinase' full_name = Column(String) uniprot_code = Column(String) def loadSession(): metadata = Base.metadata Session = sessionmaker(bind=engine) session = Session() return session @app.route("/search/kinases/<query>") def kinase_results(query): sql_session = loadSession() kinase = sql_session.query(Kinases).get(query) if kinase is None: return redirect(url_for('user_message', query=query)) name = kinase.full_name sql_session.close() 的情况下使用await。另外,我建议将连接代码放在async内,以便我们确定它已加载:

platform.ready

这在测试时,在打开连接时启动应用程序,然后将其关闭然后重新打开时似乎都可以正常工作。

enter image description here

如果需要,在进入组件时,请检查是否存在连接,然后检查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(); } (存在连接)

答案 1 :(得分: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()
    }

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

答案 2 :(得分:1)

不要使用插件进行网络检查,我有一种非常非常简单的方法来检查用户是否连接了互联网,因此我们要做的就是使用此方法:

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

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

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