如何在Ionic 4的每个页面中检查Internet连接。需要是如果出现网络错误,我需要将应用程序重定向到错误页面。
答案 0 :(得分:0)
使用以下命令安装网络信息插件:-
cordova plugin add cordova-plugin-network-information
然后,您可以在设备就绪后使用以下代码来在设备离线时执行一些代码:-
document.addEventListener("offline", onOffline, false);
function onOffline() {
// Handle the offline event
// use code to redirect here
}
答案 1 :(得分:0)
您可以尝试使用官方的Ionic Network插件(文档here)。
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 :(得分:0)
if (this.network.type === 'none') {
this.presentAlert('network was disconnected :-(');
setTimeout(() => {
navigator['app'].exitApp();
}, 4000);
}