我点击Check Connection
按钮时会运行“网络检查”,我需要在应用加载时运行它。我已经开始在一个没有成功的功能中弹出它。任何人都可以在if states == ...
找到函数语法错误吗?
点击Check Connection
import {Component} from '@angular/core';
import {NavController, Platform, AlertController} from 'ionic-angular';
declare var navigator: any;
declare var Connection: any;
@Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
constructor(public navCtrl: NavController, public platform: Platform, public alertCtrl: AlertController) { }
checkNetwork() {
this.platform.ready().then(() => {
var networkState = navigator.connection.type;
var states = {};
states[Connection.UNKNOWN] = 'Unknown connection';
states[Connection.ETHERNET] = 'Ethernet connection';
states[Connection.WIFI] = 'WiFi connection';
states[Connection.CELL_2G] = 'Cell 2G connection';
states[Connection.CELL_3G] = 'Cell 3G connection';
states[Connection.CELL_4G] = 'Cell 4G connection';
states[Connection.CELL] = 'Cell generic connection';
states[Connection.NONE] = 'No network connection';
// this. was missing
let alert = this.alertCtrl.create({
title: "Connection Status",
subTitle: states[networkState],
buttons: ["OK"]
});
// This is the proper way to present the alert
alert.present();
});
}
}
如果没有连接则显示提示
import {Component} from '@angular/core';
import {NavController, Platform, AlertController} from 'ionic-angular';
declare var navigator: any;
declare var Connection: any;
@Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
constructor(public navCtrl: NavController, public platform: Platform, public alertCtrl: AlertController) { }
ionViewDidLoad() {
this.platform.ready().then(() => {
var networkState = navigator.connection.type;
var states = {};
states[Connection.NONE] = 'No network connection';
if (states == states[Connection.NONE]) {
let alert = this.alertCtrl.create({
title: "Connection Status",
subTitle: states[networkState],
buttons: ["OK"]
});
alert.present();
}
});
}
}
答案 0 :(得分:1)
Navigator.connection
仍处于试验阶段。桌面不支持它,因此您不会在浏览器测试中获得任何有用的信息。您没有提到是否在浏览器或设备上进行测试,但可能需要注意的事项。你的代码可能没问题。
见这里:https://developer.mozilla.org/en-US/docs/Web/API/Navigator/connection
navigator.connection.type
将返回以下内容
bluetooth
cellular
ethernet
none
wifi
wimax
other
mixed
如果您将条件设置为再次测试none
,我就不明白为什么它不起作用。
...
navigator.connection.type === 'none' ? this.isOffline() : console.log('online');
}
isOffline(){
return this.alertCtrl.create({
title: 'Connection Status',
subTitle: 'No network connection',
buttons: ["OK"]
}).present();
}