Ionic 4 network check

末鹿安然 提交于 2019-12-11 10:36:53

问题


How do I check of internet connectivity in each page in Ionic 4. The need is if there is an network error I need to redirect the app to an error page.


回答1:


You can try the official Ionic Network plugin (doc here).

Usage example from doc :

import { Network } from '@ionic-native/network/ngx'; //ngx

constructor(private network: Network) { }

...

// watch network for a disconnect
let disconnectSubscription = this.network.onDisconnect().subscribe(() => {
  console.log('network was disconnected :-(');
});

// stop disconnect watch
disconnectSubscription.unsubscribe();


// 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!');
    }
  }, 3000);
});

// stop connect watch
connectSubscription.unsubscribe();



回答2:


Install network information plugin by using command:-

cordova plugin add cordova-plugin-network-information

Then you can use following code after deviceready to execute some code when the device goes offline :-

document.addEventListener("offline", onOffline, false);

function onOffline() {
    // Handle the offline event
    // use code to redirect here
}



回答3:


if (this.network.type === 'none') {
        this.presentAlert('network was disconnected :-(');
        setTimeout(() => {
            navigator['app'].exitApp();
        }, 4000);
}



来源:https://stackoverflow.com/questions/53064711/ionic-4-network-check

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!