首先在app.js中的onLaunch中写入一个你要先执行的调用方法。如图:
我这里要在最开始onload之前获取到网络状态:
getNetworkInfo()
//onLaunch异步,首页onLoad先执行bug的处理
getNetworkInfo:function(cb){
var that = this
if(that.globalData.isBtnStatus.NetworkStatus != ‘0‘){
typeof cb == "function" && cb(that.globalData.isBtnStatus.NetworkStatus)
}else{
wx.getNetworkType({
success: function(res) {
//console.log(‘onLaunch网络:‘+res.networkType);
// 返回网络类型, 有效值:wifi/2g/3g/4g/unknown(Android下不常见的网络类型)/none(无网络)
var networkType = res.networkType
if (networkType != ‘none‘) {
that.globalData.isBtnStatus.NetworkStatus = 1;
typeof cb == "function" && cb(1);
}
}
})
wx.onNetworkStatusChange(function(res) {
if (that.globalData.isBtnStatus.NetworkStatus != res.isConnected
&& true == res.isConnected) {
// WxNotificationCenter.postNotificationName("NetworkPageRefresh", true);
}
that.globalData.isBtnStatus.NetworkStatus = res.isConnected;
typeof cb == "function" && cb( that.globalData.isBtnStatus.NetworkStatus);
})
}
},
然后再在项目pages里面的首页index.js中的onload里面取值:
app.getNetworkInfo(function(retStatus){
//console.log(‘onLoad网络NetworkStatus1:‘+retStatus);
//console.log(‘onLoad网络NetworkStatus2:‘+app.globalData.isBtnStatus.NetworkStatus);
if (app.globalData.isBtnStatus.NetworkStatus == 1) {
that.networkSucc(that);
}else{
that.networkFail(that);
}
})
逻辑是:当进入onload,如果有网络就处理加载项目数据,如果没有网络就给出没网络的友好提示图片页面。
思路来源:
https://blog.csdn.net/qq_29246395/article/details/77567365
The end