Get the network status according to the network plugin
1. Install the plug-in
ionic cordova plugin add cordova-plugin-network-information
npm install --save @ionic-native/network
Two, the introduction
app.module.tsimport plugin
import {
Network } from "@ionic-native/network/ngx";
providers: [
Network
]
3. Use (introduced on the use page)
import {
Network } from '@ionic-native/network';
constructor(
public network:Network
) {
this.netWork()
}
netWork(){
// 当网络状态发生改变时触发当前方法
// network.type返回值:unknown, ethernet, wifi, 2g, 3g, 4g, cellular, none
this.network.onConnect().subscribe(
(res)=>{
console.log(‘res’ + this.network.type);
//判断手机状态是否联网,如果返回状态为none,则证明网络断开,弹框提醒
if(this.network.type === 'none'){
//ionic5自带提示框组件
const alert = await this.alertController.create({
header: "提示",
message: '请检查您的网络',
cssClass: "alertCustomCss",
buttons: ["确定"],
});
await alert.present();
}else{
//网络状态没问题后,调用后续自己要进行的方法
this.timeStatus();
}
}
(err)=>{
console.log(‘err’ + this.network.type);
}
)
}
4. Matters needing attention
4.1 Network status network.type return value:
unknown, ethernet, wifi, 2g, 3g, 4g, cellular, none
4.2 Disconnect from the network! ! !
Disconnect from the network, the return value of network.type is none, but it still takes a successful callback. For details, please find the code, where "Please check your network status" is placed.