我有一个Ionic 2应用程序,我需要知道是否有互联网连接(一般,任何类型),它是不工作的。
如果我这样做了:
if (Network.connection) {
this.af.auth.subscribe(user => {
if (user) {
this.hasSession = true;
} else {
this.hasSession = false;
}
});
} else {
// Go to home
}docs说要使用Network.type,但是编辑器说这个属性不存在,而对于Network.connection (它的描述说它返回一个带有internet类型的字符串)总是返回undefined。
编辑:
import { Network } from 'ionic-native';
declare var navigator: any;
declare var Connection: any;
@Component({
......
})
export class .... {
constructor(....) {}
ionViewDidLoad(): void {
this.retrieveAllPractises();
}
public retrieveAllPractises(): void {
let networkState = navigator.connection.type;
let isOnline = networkState != Connection.NONE;
this.showLoading();
if (isOnline) {
firebase.database().ref('/audios').once('value')
.then((snapshot) => {
let retrievedArray = snapshot.val();
for (let entry of retrievedArray) {
let practise: Practise = {
id: entry.id,
img: '',
children : entry.children,
name : entry.name,
new : entry.new,
permission : entry.permission,
type : entry.type
};
practise.img = this.practiseImg(practise);
this.practises.push(practise);
}
this.addDownloadItem();
this.hideLoading();
});
} else {
this.addDownloadItem();
this.hideLoading();
this.showOfflineStatusMsg();
}
}
}使用此代码:
发布于 2017-02-23 20:55:46
在您的组件/服务中,上述类定义中添加:
declare var navigator: any;
declare var Connection: any;这比允许您执行以下操作更重要:
let networkState = navigator.connection.type;
let isOnline = networkState != Connection.NONE;编辑
为了使用上面的内容,您还应该安装以下cordova插件:
ionic plugin add cordova-plugin-network-information --save发布于 2017-02-23 21:38:36
要使Network.type正常工作,您的ionic-native版本必须高于2.2.12,然后可以使用
if (Network.type == 'NONE') {
//some code
} else {
// Go to home
}您还可以查看Ionic中的网络插件文档,查看您可以比较哪些连接类型,如4g、3g、wifi、2g、以太网等。如果您愿意,您也可以创建一个Network.onDisconnect().subscribe()来查看用户是否断开连接,以便将他发送到主页。
希望能帮上忙。
https://stackoverflow.com/questions/42425907
复制相似问题