问题
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