wx.onNetworkStatusChange(function (res) 监听网络状态变化 实践方案
网络状态 · 小程序 https://developers.weixin.qq.com/miniprogram/dev/api/device.html#wxonnetworkstatuschangecallback
import wepy from 'wepy' import util from './util' import md5 from './md5' // import tip from './tip' const networkStatusChangeLog = () => { try { wx.removeStorageSync('onNetworkStatusChange') } catch (e) { // Do something when catch error console.log(e) } const log = new Date().toUTCString() + 'BizInfo' + 'uploadWhenOk' wx.setStorageSync('onNetworkStatusChange', log) } const isConnected = async () => { let container = {} await wx.getNetworkType({ success: function (res) { container = res console.log(res) }, fail: function (res) {}, complete: function (res) {} }) await wx.onNetworkStatusChange(function (res) { console.log('onNetworkStatusChange',res) }) // console.log(container) // if (!container.networkStatus.isConnected) { // wx.showToast({ // title: '无网络', // icon: 'loading', // duration: 2000 // }) // networkStatusChangeLog() // return false // } return true } const appendInfo = () => { const API_SECRET_KEY = 'https://github.com/dyq086/wepy-mall/tree/master/src' const TIMESTAMP = util.getCurrentTime() const SIGN = md5.hex_md5((TIMESTAMP + API_SECRET_KEY).toLowerCase()) const MORE = 'more......' return { 'API_SECRET_KEY': API_SECRET_KEY, 'TIMESTAMP': TIMESTAMP, 'SIGN': SIGN, 'MORE': MORE } } const wxRequest = async (params = {}, url) => { console.log('wxRequest', params) const c = await isConnected() if (!c) { return } // tip.loading() let data = params.query || {} const header = params.header || {} const isAppend = params.isAppend || false if (isAppend) { const a = appendInfo() for (let k in a) { eval('data.' + k + '= a.' + k) } } let res = await wepy.request({ url: url, method: params.method || 'GET', data: data, header: header }) // tip.loaded() console.log('wxRequest', res) return res } module.exports = { wxRequest }
和声明的位置无关,一次声明,整个小程序 都在使用
所以放到
app.wpy?
1、在回调函数中添加本地存储的代码,每次监听到网络状态变化都会在本地记录,然后给用户弹出提醒框;
2、声明一次;
3、在请求网络的公共方法处添加网络状态钩子,方式为读取1中的本地的网络数据。
D:\GPUGO\MP\wepy\mpBMCwepy\src\app.wpy
<style lang="less"> .container { height: 100%; display: flex; flex-direction: column; align-items: center; justify-content: space-between; box-sizing: border-box; } </style> <script> import wepy from 'wepy' import 'wepy-async-function' import { setStore } from 'wepy-redux' import configStore from './store' const store = configStore() setStore(store) export default class extends wepy.app { config = { pages: [ // 'pages/index', 'pages/advertisement', 'pages/companyShow', 'pages/logs', 'pages/materialUpload', 'pages/news', 'pages/questionsAnswers', 'pages/userCenter', 'pages/consumeRecord', 'pages/companyInfo', 'pages/userInfo', 'pages/userLogin', 'pages/videoUpload', 'pages/aboutUs', 'pages/recharge', 'pages/helpCenter', 'pages/commonService', 'pages/cloundAd', 'pages/cloundNews', 'pages/cloundSEM', 'pages/companyQA', 'pages/companyBK', 'pages/shortVideo', 'pages/newsWebView' 'pages/index', 'pages/news', 'pages/userCenter', 'pages/newsWebView', 'pages/userLogin', 'pages/companyInfo', 'pages/personalInfo' ], window: { backgroundTextStyle: 'light', navigationBarBackgroundColor: '#fff', navigationBarTitleText: 'WeChat', navigationBarTextStyle: 'black' }, tabBar: { list: [{ pagePath: 'pages/index', text: '首wepy', iconPath: 'images/bar1a.png', selectedIconPath: 'images/bar1b.png' }, { pagePath: 'pages/news', text: '资讯', iconPath: 'images/bar2a.png', selectedIconPath: 'images/bar2b.png' }, { pagePath: 'pages/userCenter', text: '我的', iconPath: 'images/bar3a.png', selectedIconPath: 'images/bar3b.png' } ] } } customData = { common: { apiUrl: 'http://api.dev.com:8000/', imgUrlMP: 'http://blackhole.dev.com/images/', imgUrlBiz: 'http://api.dev.com:8000/', dataEyePath: 'http://blackhole.dev.com:50000', localImgPath: 'http://blackhole.dev.com/images/' } } globalData = { userInfo: null } constructor() { super() this.use('requestfix') this.use('promisify') } networkStatusChangeLog() { const log = new Date().toUTCString() + 'BizInfo' + 'uploadWhenOk' wx.setStorageSync('onNetworkStatusChangeLog', log) } onLaunch() { const updateManager = wx.getUpdateManager() updateManager.onCheckForUpdate(function(res) { // 请求完新版本信息的回调 console.log(res) console.log(res.hasUpdate) }) updateManager.onUpdateReady(function() { wx.showModal({ title: '更新提示', content: '新版本已经准备好,是否重启应用?', success: function(res) { if (res.confirm) { // 新的版本已经下载好,调用 applyUpdate 应用新版本并重启 updateManager.applyUpdate() } } }) }) updateManager.onUpdateFailed(function() { // 新的版本下载失败 }) let that = this wx.onNetworkStatusChange(function(res) { that.networkStatusChangeLog() wx.setStorageSync('onNetworkStatusChange', res) if (!res.isConnected) { wx.showToast({ title: '无网络', icon: 'loading', duration: 2000 }) } }) } sleep(s) { return new Promise((resolve, reject) => { setTimeout(() => { resolve('promise resolved') }, s * 1000) }) } async testAsync() { const data = await this.sleep(3) console.log(data) } getUserInfo(cb) { const that = this if (this.globalData.userInfo) { return this.globalData.userInfo } wepy.getUserInfo({ success(res) { that.globalData.userInfo = res.userInfo cb && cb(res.userInfo) } }) } onShareAppMessage(title = 'MBC') { return { title: title, success: function(res) {}, fail: function(res) {} } } } </script>
D:\GPUGO\MP\wepy\mpBMCwepy\src\utils\wxRequest.js
import wepy from 'wepy' import util from './util' import md5 from './md5' // import tip from './tip' const appendInfo = () => { const API_SECRET_KEY = 'https://github.com/dyq086/wepy-mall/tree/master/src' const TIMESTAMP = util.getCurrentTime() const SIGN = md5.hex_md5((TIMESTAMP + API_SECRET_KEY).toLowerCase()) const MORE = 'more......' return { 'API_SECRET_KEY': API_SECRET_KEY, 'TIMESTAMP': TIMESTAMP, 'SIGN': SIGN, 'MORE': MORE } } const wxRequest = async (params = {}, url) => { console.log('wxRequest', params) const c = wx.getStorageSync('onNetworkStatusChange') if (!c.isConnected) { wx.showToast({ title: '无网络', icon: 'loading', duration: 2000 }) return } // tip.loading() let data = params.query || {} const header = params.header || {} const isAppend = params.isAppend || false if (isAppend) { const a = appendInfo() for (let k in a) { eval('data.' + k + '= a.' + k) } } let res = await wepy.request({ url: url, method: params.method || 'GET', data: data, header: header }) // tip.loaded() console.log('wxRequest', res) return res } module.exports = { wxRequest }
globalData = { userInfo: null, onNetworkStatusChangeRes:{} } constructor() { super() this.use('requestfix') this.use('promisify') } networkStatusChangeLog() { const log = new Date().toUTCString() + 'BizInfo' + 'uploadWhenOk' wx.setStorageSync('onNetworkStatusChangeLog', log) } onLaunch() { const updateManager = wx.getUpdateManager() updateManager.onCheckForUpdate(function(res) { // 请求完新版本信息的回调 console.log(res) console.log(res.hasUpdate) }) updateManager.onUpdateReady(function() { wx.showModal({ title: '更新提示', content: '新版本已经准备好,是否重启应用?', success: function(res) { if (res.confirm) { // 新的版本已经下载好,调用 applyUpdate 应用新版本并重启 updateManager.applyUpdate() } } }) }) updateManager.onUpdateFailed(function() { // 新的版本下载失败 }) let that = this wx.onNetworkStatusChange(function(res) { that.networkStatusChangeLog() that.globalData.onNetworkStatusChangeRes=res if (!res.isConnected) { wx.showToast({ title: '无网络', icon: 'loading', duration: 2000 }) } }) }