如何在ionic2 app中检测运行时的互联网连接?

时间:2017-04-18 20:24:34

标签: cordova ionic-framework ionic2

我真的需要你的帮助。我试图检测我的Ionic 2移动应用上是否有互联网连接。我需要随时知道移动设备是否丢失连接以及何时恢复连接,如果有wifi连接......那么观察者和网络Cordova插件的wifi检测,就是我需要的 为了实现这一点,我在页面构造函数中有两个使用者(用于连接和断开连接)来设置我在页面逻辑中使用的布尔实例变量。这是我的代码

app.component.ts

import { NgModule, ErrorHandler } from '@angular/core';
import { IonicApp, IonicModule, IonicErrorHandler } from 'ionic-angular';
import { MyApp } from './app.component';

import { HomePage } from '../pages/home/home';
import { Geolocation } from '@ionic-native/geolocation';
import { Network } from '@ionic-native/network';
//import { Network } from 'ionic-native';
import { StatusBar } from '@ionic-native/status-bar';
import { SplashScreen } from '@ionic-native/splash-screen';

 @NgModule({
    declarations: [
      MyApp,
      HomePage
    ],
    imports: [
      IonicModule.forRoot(MyApp)
    ],
    bootstrap: [IonicApp],
    entryComponents: [
       MyApp,
       HomePage    
    ],
    providers: [
      StatusBar,
      SplashScreen,
      {provide: ErrorHandler, useClass: IonicErrorHandler},    
      Geolocation,
      Network
   ]
  })
  export class AppModule {}




home.ts

import { Component } from '@angular/core';
import { NavController, Platform } from 'ionic-angular';
import { Geolocation } from '@ionic-native/geolocation';
import { Network } from '@ionic-native/network';


@Component({
 selector: 'page-home',
 templateUrl: 'home.html'
})
 export class HomePage {

private online:boolean = false;
private wifi:boolean = false;
public disconnectSubscription:any;
public connectSubscription:any;

constructor(private nav: NavController, private geolocation: Geolocation, private network: Network, private platform: Platform) {  
    this.platform.ready().then( () => {
      //listener
      this.connectSubscription = this.network.onConnect().subscribe(() => {
          alert('connected!');
          this.online = true;

          setTimeout(() => {
            // before we determine the connection type.  Might need to wait
            if (this.network.type === 'wifi') {
              this.hayWIFI;
              alert('wifi connection');
            }
          }, 3000);
      });

      //listener
      this.disconnectSubscription = this.network.onDisconnect().subscribe(() => {            
          this.online = false;
          alert('without connection!');
      });
    });
}

}

问题是事件是像onchange事件一样触发的..当我手动取出移动设备的连接或者应用程序从休眠状态恢复时(当连接丢失时),我只看到警报,< strong>但不是应用程序刚刚初始化时 :(我在主页甚至在MyApp页面(app.component.ts)上尝试过构造函数提示符,但没有成功

我做错了什么?我怎样才能满足要求?互联网上有许多不同的方法,但看起来更老,甚至在导入网络服务方面也有所不同。我的离子信息是

离子框架:2.3.0
离子应用程序脚本:1.1.4
角核:2.4.8
Angular Compiler CLI:2.4.8
节点:6.4.0
OS平台:Windows 10
导航平台:Win32
用户代理:Mozilla / 5.0(Windows NT 10.0; WOW64)AppleWebKit / 537.36(KHTML,与Gecko一样)Chrome / 57.0.2987.133 Safari / 537.36

提前致谢

2 个答案:

答案 0 :(得分:8)

如果您想在组件(页面)中收听网络状态,我建议您在其中一个页面生命周期事件中执行此操作,例如ionViewDidLoad()ionViewDidEnter()。通常,您希望确保构造函数尽可能少地处理逻辑,因为它只会触发一次。您可以阅读有关他们的更多信息here

在我的应用程序中,我在一个提供程序中侦听网络状态,该提供程序充当Angular HTTP模块的包装器。为了实现这一点,我必须初始化platform.ready()块内的所有逻辑,以确保设备实际上已准备好开始被操作。这是我的提供商的样子:

export class HTTP {
  public online:boolean = true;
  public base:string; // this will be set in the constructor based on if we're in dev or prod
  public token:string = null;

  constructor(public platform:Platform, public http: Http, public events:Events, public cache:CacheService, private network:Network) {
    if(document.URL.includes('https://') || document.URL.includes('http://')){
      this.base = "http://127.0.0.1:3001/";
    } else {
      this.base = "https://url.to_actual_URL.com/";
    }

    this.platform.ready().then(() => {
      let type = this.network.type;

      //console.log("Connection type: ", this.network.type);
      // Try and find out the current online status of the device
      if(type == "unknown" || type == "none" || type == undefined){
        //console.log("The device is not online");
        this.online = false;
      }else{
        //console.log("The device is online!");
        this.online = true;
      }
    });

    this.network.onDisconnect().subscribe( () => {
      this.online = false;
      //console.log('network was disconnected :-(');
    });

    this.network.onConnect().subscribe( () => {
      this.online = true;
      //console.log('network was connected :-)');
    });
  }
}

答案 1 :(得分:0)

我使用ngcordova解决了类似的问题。它为你提供了一个实现承诺的插件的角度包装器。

当您尝试调用Cordova插件时,Cordova插件通常都没有准备好,使用promise接口可以避免出现未定义的错误。

我从网络插件的ngcordova页面偷了这个例子。

module.controller('MyCtrl', function($scope, $rootScope, $cordovaNetwork) {

 document.addEventListener("deviceready", function () {

    var type = $cordovaNetwork.getNetwork()

    var isOnline = $cordovaNetwork.isOnline()

    var isOffline = $cordovaNetwork.isOffline()


    // listen for Online event
    $rootScope.$on('networkOffline', function(event, networkState){
      var onlineState = networkState;
    })

    // listen for Offline event
    $rootScope.$on('networkOffline', function(event, networkState){
      var offlineState = networkState;
    })

  }, false);
});