zoukankan      html  css  js  c++  java
  • 解决微信小程序中在其他页面无法使用app.js中获取的userInfo或openid的问题

    解决微信小程序中在其他页面无法使用app.js中获取的userInfo或openid的问题

    https://blog.csdn.net/mayuko2012/article/details/78252870

    Hades_Dev 2017-10-16 18:53:12 19029 收藏 7
    展开
    问题
    最近写小程序中,在app.js里获取用户的openid和userinfo,并存储为全局变量:

    getUserInfo: function () {
    var that = this
    wx.getUserInfo({
    success: function (res) {
    console.log('用户信息', res.userInfo)
    that.globalData.userInfo = res.userInfo
    }
    })
    },
    1
    2
    3
    4
    5
    6
    7
    8
    9
    然而当在index中调用getApp().globalData.userOpenid时却返回为空值。

    原因
    因为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)
    }
    })
    }
    },
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    在其他需要使用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)
    })

    },
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11

    ————————————————
    版权声明:本文为CSDN博主「Hades_Dev」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
    原文链接:https://blog.csdn.net/mayuko2012/java/article/details/78252870

  • 相关阅读:
    WPF 进度条
    WPF CPU使用率线性表
    Android annotation
    git 操作
    git 合并指定目录到master
    远程连接mysql报错,ERROR 1045 (28000): Access denied for user 'ODBC'@'localhost' (using password: NO)解决方案
    centos7 安装python2.7.14 并与原版本共存
    pycahrm 断点调试
    ImportError: No module named Crypto.Cipher 报错解决方法
    python操作 rabbitMQ
  • 原文地址:https://www.cnblogs.com/dabaixiong/p/12901857.html
Copyright © 2011-2022 走看看