我真的需要你的帮助。我正在尝试检测Ionic 3移动应用程序上是否有Internet连接。它工作正常。但是这次我必须关闭互联网,现在我必须单击任何链接,现在这种情况下,只有在互联网打开的情况下,我们才可以推送页面。我不知道如何再次触发onDisconnect功能?
//app.component.ts file
listenConnection(){
// watch network for a disconnection if user is offline.......
let disconnectSubscription = this.network.onDisconnect().subscribe(() => {
//show alert....
const alert = this.alertCtrl.create({
title: 'Your Data is off',
message : 'Turn on data or wifi in setting',
buttons: [
{
text: 'Ok',
handler: (data: any) => {
console.log('data');
}}
],
enableBackdropDismiss: false
});
alert.present();
});
// watch network for a connection
let connectSubscription = this.network.onConnect().subscribe(() => {
// 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.
if (this.network.type === 'wifi') {
console.log('data');
}
});
}
它正在正常工作,但是问题是假设我的警报已打开,并且在单击“确定”按钮后我们收到了关闭警报。现在,我必须单击任何其他链接,现在网络已经关闭,只有在Internet开启时告诉我们,任何人,如何管理此情况,我们才有推送页面。
答案 0 :(得分:2)
因此,通常您希望在具有很多页面的应用程序中执行此操作的方式:
您的提供者应该是这样的:
import { Injectable, AlertController } from '@angular/core';
import { Network } from "@ionic-native/network";
@Injectable()
export class FoundationProvider {
public appIsOnline: boolean;
constructor(
private network: Network,
private alertCtrl: AlertController
) {
this.appIsOnline = true;
this.listenConnection();
}
listenConnection() {
// watch network for a disconnection if user is offline.......
let disconnectSubscription = this.network.onDisconnect().subscribe(() => {
this.appIsOnline = false;
//show alert....
const alert = this.alertCtrl.create({
title: 'Your Data is off',
message: 'Turn on data or wifi in setting',
buttons: [
{
text: 'Ok',
handler: (data: any) => {
console.log('data');
}
}
],
enableBackdropDismiss: false
});
alert.present();
});
// watch network for a connection
let connectSubscription = this.network.onConnect().subscribe(() => {
this.appIsOnline = true;
// 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.
if (this.network.type === 'wifi') {
console.log('data');
}
});
}
}
然后每个页面都需要导入此提供程序,将其注入到构造函数中,然后将钩子添加到页面中:
ionViewCanEnter(): boolean {
if(this.foundationProvider.appisOnline) {
return true;
}
return false;
}
或者,根据您应用的确切结构,您可以“保护”用于导航到页面的.push,.setRoot等方法。但是您应该共享更多代码,以提供更好的建议。