解决微信小程序中在其他页面无法使用app.js中获取的userInfo或openid的问题
温馨提示:
最后更新时间2018-09-01 20:53:50,若内容或图片失效,请留言反馈!
问题
最近写小程序中,在app.js里获取用户的openid和userinfo,并存储为全局变量:
getUserInfo: function () {var that = thiswx.getUserInfo({success: function (res) {console.log('用户信息', res.userInfo)that.globalData.userInfo = res.userInfo}})},
然而当在index中调用getApp().globalData.userOpenid时却返回为空值。
原因
因为wx.getUserInfo为异步获取的信息。
解决方式
将getuserInfo改为回调函数:
getUserInfo: function (cb) {var that = thisif (this.globalData.userInfo) {typeof cb == "function" && cb(this.globalData.userInfo)} else {wx.getUserInfo({success: function (res) {console.log('用户信息', res.userInfo)that.globalData.userInfo = res.userInfotypeof cb == "function" && cb(that.globalData.userInfo)}})}},
在其他需要使用userinfo的页面中通过getApp().getUserInfo(function(userinfo){console.log(userinfo);})这种方式调用。
或者在onload函数中:
转载:https://blog.csdn.net/mayuko2012/article/details/78252870onLoad: function (options) {var that = thisgetApp().getUserOpenid(function (openid) {that.setData({userName: getApp().globalData.userInfo.nickName,userOpenid: openid})console.log('用户openid', that.data.userOpenid)})},
文章版权声明:除非注明,否则均为林羽凡原创文章,转载或复制请以超链接形式并注明出处。