app.js中获取用户的openid和userinfo,并存储为全局变量,当在index中调用getApp().globalData.userInfo时却返回为空值:
getUserInfo: function () {
var that = this
wx.getUserInfo({
success: function (res) {
console.log('用户信息', res.userInfo)
that.globalData.userInfo = res.userInfo
}
})
},
原因:
微信小程序中wx.getUserInfo为异步获取信息
将getuserInfo改为回调函数:
getUserInfo: function (cb) {
var that = this
if (this.globalData.userInfo) {
typeof cb == "function" && cb(this.globalData.userInfo)
} else {
wx.getUserInfo({
success: function (res) {
console.log('用户信息', res.userInfo)
that.globalData.userInfo = res.userInfo
typeof cb == "function" && cb(that.globalData.userInfo)
}
})
}
},
在其他需要使用userinfo的页面中,可直接用以下代码:
getApp().getUserInfo(function(userinfo){
console.log(userinfo);})
或在onload函数中:
onLoad: function (options) {
var that = this
getApp().getUserOpenid(function (openid) {
that.setData({
userName: getApp().globalData.userInfo.nickName,
userOpenid: openid
})
console.log('用户openid', that.data.userOpenid)
})
},