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