我制作了检测网络状态的函数,当我在浏览器或离子视图应用程序上测试此功能时,一切都可以正常工作。
当我在我的安卓设备上安装我的应用程序时,我的问题发生了,我关闭了我的 wifi,但没有任何反应。
这是我的代码:
constructor(...){
platform.ready().then(() => {
...
this.checkConnection();
})
}
checkConnection(){
this.network.onConnect().subscribe(data => {
console.log(data);
//this.displayNetworkUpdate(data.type);
if(this.isOffline==true){
this.isOffline=false;
this.toast.dismiss();
}
}, error => console.error(error));
this.network.onDisconnect().subscribe(data => {
console.log(data)
//this.displayNetworkUpdate(data.type);
if(this.isOffline==false){
this.isOffline=true;
this.toast= this.toastCtrl.create({
message: 'No Internet connection. Make sure that Wi-Fi or Cellular mobile data is turned on, then continue using the application.',
duration: 99999999999
});
this.toast.present();
}
}, error => console.error(error));
}
我的理解是,这些可观察量用于状态的变化。 请参阅我创建的此解决方案。
providers/LastKnownNetworkState.ts
import {Injectable} from '@angular/core';
import {Network} from '@ionic-native/network';
@Injectable()
export class LastKnownNetworkState {
online: boolean;
constructor(private network: Network) {
// can get the initial state.
this.online = navigator.onLine;
// these will capture change in state
this.network.onDisconnect().subscribe(() => {
this.online = false;
});
this.network.onConnect().subscribe(() => {
this.online = true;
});
}
isOnline(): boolean {
return this.online;
}
}