2017-04-18 65 views
3

我真的需要你的帮助。我正在尝试检测我的Ionic 2移动应用上是否有互联网连接。我需要知道在任何时候如果手机丢失连接,当它恢复它,也如果有wifi连接..所以观察员和无线网络Cordova插件检测,只是做我所需要的 为了实现,我有两个订户(用于连接和断开连接)在页面构造函数中设置一个布尔实例变量,我使用了整个页面逻辑。这里是我的代码我如何检测在ionic2应用程序运行时的互联网连接?

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事件。我只看到了警报,当我手动取出手机或即使应用的连接从睡眠中恢复(当它失去连接时),,但不是当应用刚刚初始化时 :(我在主页上尝试过构造函数suscriptors',甚至在MyApp页面(app.component.ts)没有成功

我在做什么错了?我怎样才能达到要求?有很多dife租金在互联网上的批准,但看起来更老,甚至在网络服务的进口有所不同。我的离子信息是

离子框架:2.3.0
离子应用程序脚本:1.1.4
方芯:2.4.8
角度编译CLI:2.4.8
节点:6.4.0
OS平台:视窗10
导航平台:的Win32
用户代理:Mozilla的/ 5.0(Windows NT的10.0; WOW64)为AppleWebKit/537.36(KHTML,例如Gecko)铬/ 57.0.2987.133 Safari浏览器/ 537.36

由于事先

回答

5

如果您想要监听组件(页面)中的网络状态,我建议您在页面生命周期事件之一中执行此操作,例如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 :-)'); 
    }); 
    } 
} 
+0

非常感谢您的回答!我把听众放在一些页面生命周期事件的方法上,但行为仍然很奇怪:当应用程序初始化时,有时候它有效,有时却不行。但现在我检查这个网络。在启动时键入属性,我有我需要的功能:) – jmann

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); 
}); 
+0

这不是Angular 2+,因此不是Ionic 2的例子 – krzychek