怎么在index.js中获取app.js中的全局变量

发布于 7 年前作者 jinggu10656 次浏览最后编辑 7 年前来自 ask

app.js页面App({  globalData: {    userInfo: “”,    js_code: “”,    openid: “”,    session_key: “”  },  getUserInfo: function (cb) {    var that = this;    if (that.globalData.userInfo) {      typeof cb == “function” && cb(that.globalData.userInfo)    } else {      wx.login({        success: res => {          that.globalData.js_code = res.code          wx.getUserInfo({            success: res => {              that.globalData.userInfo = res.userInfo;              typeof cb == “function” && cb(that.globalData.userInfo);              // 请求官方接口,获取openid和session_key              wx.request({                url: “https://api.weixin.qq.com/sns/jscode2session”,                data: {                  appid: “********”,                  secret: “*******”,                  js_code: that.globalData.js_code,                  grant_type: “authorization_code”                },                success: function (res) {                  that.globalData.openid = res.data.openid;                  that.globalData.session_key = res.data.session_key;                                  },                fail: function () {                }              })            }          })        }      })    }  }})index.js页面Page({  data: {    userInfos:{}  },  onLoad: function (options) {    var that = this;    app.getUserInfo();        console.log(app.globalData);  }})

在index中打印app.globalData结果是下图,而直接调用全局变量会得到初始值"",应该怎么解决?怎么获取下面的数据?

 

10 回复
yang31
yang311 楼6 年前

这个问题解决了没?

xiawen
xiawen2 楼6 年前

getApp().globalData

xiuyinglai
xiuyinglai3 楼6 年前

楼主 问题解决了吗

yongjin
yongjin4 楼6 年前

表示我也遇到了

tding
tding5 楼6 年前

看样子是异步的问题噶。

qianmin
qianmin6 楼6 年前

楼主,你的问题解决了没有啊? 小弟我也遇到了这个问题。

sliu
sliu7 楼6 年前

注意看一下我的截图

xiongqiang
xiongqiang8 楼6 年前

那怎么解决呢?

jlong
jlong9 楼6 年前

这个问题怎么办啊

liaojun
liaojun10 楼5 年前

getApp().globalData得到的是初始值,不是动态改变后的值。