其他页面无法获取app.js中的全局数据
发布于 6 年前 作者 xuwei 17886 次浏览 来自 问答

App({

globalData: {

g_isPlayingMusic: false,

g_currentMusicPostId: null,

doubanBase: https://api.douban.com,

g_userInfo: null

},

onLaunch: function () {

// 展示本地存储能力

// 登录

wx.login({

success: res =>{

// 发送 res.code 到后台换取 openId, sessionKey, unionId

if (res.code) {

console.log(‘获取用户登录态成功!’ + res.errMsg)

//发起网络请求,与后台服务器进行验证

} else {

console.log(‘获取用户登录态失败!’ + res.errMsg)

}

}

})

wx.getSetting({

success: res => {

if (res.authSetting[‘scope.userInfo’]) {

// 已经授权,可以直接调用 getUserInfo 获取头像昵称,不会弹框

wx.getUserInfo({

success: res => {

// 可以将 res 发送给后台解码出 unionId

this.globalData.g_userInfo = res.userInfo

// 由于 getUserInfo 是网络请求,可能会在 Page.onLoad 之后才返回

// 所以此处加入 callback 以防止这种情况

if (this.userInfoReadyCallback) {

this.userInfoReadyCallback(res)

}

}

})

}

}

})

}

})

这里,获取用户的信息,但是在别的页面使用var app = getApp();

var avatarUrl = app.globalData.g_userInfo.avatarUrl;

这段代码,avatarUrl 有一半概率获取不到,会抛出如下异常:

thirdScriptError Cannot read property ‘avatarUrl’ of null;at pages/welcome/welcome page lifeCycleMethod onLoad function TypeError: Cannot read property ‘avatarUrl’ of null;

模拟器上调试5次,有2次获取不到,3次获取到;手机调试,一次都获取不到。

1 回复

在获取数据的函数写在onReady函数里,就能获取到~之前是写在onLoad函数里~

回到顶部