【发布时间】:2017-09-14 20:18:58
【问题描述】:
我真的需要你的帮助。我正在尝试检测我的 Ionic 2 移动应用程序上是否有互联网连接。我需要随时知道移动设备是否丢失连接以及何时恢复连接,以及是否有 wifi 连接.. 所以观察者和 Network 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 事件一样被触发。我只在手动断开手机连接或应用程序从睡眠中恢复时(当它失去连接时)看到警报,但不是在应用程序刚刚初始化时 :(我在主页甚至在 MyApp 页面 (app.component.ts) 都尝试了构造函数 suscriptors' 但没有成功
我做错了什么?我怎样才能达到要求?互联网上有许多不同的方法,但看起来更旧,甚至在网络服务的导入方面也有所不同。我的离子信息是
离子框架:2.3.0
离子应用脚本:1.1.4
角核心:2.4.8
Angular 编译器 CLI:2.4.8
节点:6.4.0
操作系统平台:Windows 10
导航平台:Win32
用户代理:Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36
提前致谢
【问题讨论】:
标签: cordova ionic-framework ionic2