最近做公司的小程序项目时遇到一个问题,通过小程序分享出去的链接进入小程序,进入活动页面,在页面onload()方法中获取全局变量uid,根据uid获取用户信息,结果发现uid为空(开发者工具中运行正常),代码如下
app.js onlauch()中进行登录操作获取用户Uid ,存到全局变量 app.config.uid
login: function (code) { var that = this; wx.request({ url: `${this.config.host}/app/wxlogin/`, method: "GET", data: { appid: this.config.appid, code: code }, header: { 'content-type': 'json' }, success: function (res) { if (res.data.code == 0) { that.config.uid = res.data.data.uid that.config.headimg = res.data.data.headimg that.config.name = res.data.data.name } else { console.log("login failed. res=%s", res.data.msg) } } }) },activity.js onLoad中根据全局变量uid 获取用户信息
const app = getApp() ... onLoad: function () { wx.showLoading({ title: '加载中', }) this.fetchData(app.config.uid); },经过分析后,得出该问题的原因是,app.js中登录操作是异步操作,acitvity.js的fetchData()在app.js登录前先执行了,故uid为空,上网找了解决方案,有的说 settimeout(),在页面加载时等待几秒待app.js跑完再执行接下来的操作,这样确实有可能解决问题,但是做不到实时的在app.js执行后紧接执行。另外有人说用promise写回调,但是由于我们的登录操作写在app.js的onlauch中,另外在写一个promise回调,会造成两次登录请求。
几经折腾,最后得到一种比较适合的决解方案,代码如下
app.js
login: function (code) { var that = this; wx.request({ url: `${this.config.host}/app/wxlogin/`, method: "GET", data: { appid: this.config.appid, code: code }, header: { 'content-type': 'json' }, success: function (res) { if (res.data.code == 0) { that.config.uid = res.data.data.uid that.config.headimg = res.dara.data.headimg that.config.name = res.data.data.name //判断app.js是否有uidCallback方法,有则将uid作为参数调用该方法 if (that.uidCallback) { that.uidCallback(that.config.uid) } } else { console.log("login failed. res=%s", res.data.msg) } } })},activity.js
const app = getApp() ...onLoad: function () { wx.showLoading({ title: '加载中', }) if (!!app.config.uid) { //无uid,需等待APP.js回调 const that = this; app.uidCallback = res => { //给app.js对象定义回调函数,待app.js调用 that.setData({ uid: res }) app.config.uidCallback = false //回调完成注销该方法 that.fetchData(res); } } else { this.fetchData(app.config.uid); }activity.js进入页面先判断有无uid,有则执行之后的操作,没有则在app对象上定义uidCallback方法,将之后的操作写在uidCallback方法中等待app.js回调,等到app.js登录完毕,判断app对象有无uidCallback方法,有则执行该方法返回uid。这是目前看来较佳的解决方案。













