我真的需要你的帮助。我正在尝试检测我的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
由于事先
非常感谢您的回答!我把听众放在一些页面生命周期事件的方法上,但行为仍然很奇怪:当应用程序初始化时,有时候它有效,有时却不行。但现在我检查这个网络。在启动时键入属性,我有我需要的功能:) – jmann