2017-10-19 144 views
0

我做了检测网络状态的功能,当我在浏览器或离子视图应用上测试此功能时,每件事情都正常工作。离子2的网络检测不能正常工作

当我在我的Android设备上安装我的应用程序时,发生了问题,我关掉了我的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)); 
} 

回答

0

我的理解是,这些观测值都在状态的变化。看到我创建的解决方案。

提供商/ 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; 
    } 

}