首页 > 微信 > 详细

微信小程序填坑之旅(1)-app.js中用云开发获取openid,在其他页上用app.globaldata.openid获取为空

时间:2019-09-12 20:00:03      阅读:962      评论:0      收藏:0      [点我收藏+]

参考:小程序如何在其他页面监听globalData中值的变化?https://www.jianshu.com/p/8d1c4626f9a3

原因就是:app.js没执行完时,其他页已经onload了,所以取不到globalData

解决办法就是用回调函数

app.js

//app.js
App({
  globalData: { },

  onLaunch: function() {
    },
  //获取openid,由于网络延时,通常在其他页onload之后才会success,所以从其他页传回调函数cb进来。
  getopenid: function(cb) { 
    if (this.globalData.openid) {
      typeof cb == "function" && cb(this.globalData.openid)
    } else {
var that = this wx.cloud.callFunction({ name:
login, data: {}, success: res => { //闭包函数内,可以用this,而不需要用that=this that.globalData.openid = res.result.openid typeof cb == "function" && cb(that.globalData.openid) }, fail: err => { wx.showToast({ icon: none, title: 获取 openid 失败,请检查 login 云函数, }) console.log([云函数] [login] 获取 openid 失败,请检查是否有部署云函数,错误信息:, err) }, }) } }, })

在其他页面上,onload中 const app = getApp()   用app.getopenid调用app.js中的函数,并传入参数that.cb 

  onLoad: function(options) {
    //设置回调,防止小程序globalData拿到数据为null     
    let that = this;
    app.getopenid(that.cb)

  },
  cb: function(res) {
    let that = this
    console.log("write cb res", res)
    that.setData({
      openid: res
    })
  },

这样当App.js中的getopenid有返回值时,就会更新到其他页面

还可以将that.cb写成闭包函数,就不用 let that =this了

  onLoad: function(options) {
    //设置回调,防止小程序globalData拿到数据为null    
    app.getopenid(res => {
      console.log("write cb res", res)
      this.setData({
        openid: res
      })
    })
  },

 

微信小程序填坑之旅(1)-app.js中用云开发获取openid,在其他页上用app.globaldata.openid获取为空

原文:https://www.cnblogs.com/pu369/p/11514527.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!