支付宝小程序开发练习-重构,在app.js获取用户信息(二)

App({
  getUserInfo(){
    return new Promise((resovle,reject)=>{
      if(this.userInfo) resovle(this.userInfo);
      //调用用户授权 api 获取用户信息
      my.getAuthCode({
        success:(authcode) =>{
          console.info(authcode);
          
          my.getAuthUserInfo({
            scopes: ['auth_user'],
            success: (res) => {
              this.userInfo = res;
              resovle(this.userInfo);
            },
            fail:() =>{
              reject({});
            }
          });
        },
        fail:() =>{
          reject({});
        }
      });
    });
  },

  onLaunch(options) {
    // 第一次打开
    // options.query == {number:1}
    console.info('App onLaunch');
  },
  onShow(options) {
    // 从后台被 scheme 重新打开
    // options.query == {number:1}
  },
});

Index.js 中通过 调用 app.js 中定义的 getUserInfo 获取用户信息,这样只要需要获取用户信息的页面都可以调用这个函数

const app = getApp();

Page({
  data: {
    src: ''
  },
  imageError: function (e) {
    console.log('image 发生错误', e.detail.errMsg)
  },
  imageLoad: function (e) {
    console.log('image 加载成功', e);
  },
  onLoad(query) {
    // 页面加载
  },
  onReady() {
    // 页面加载完成
    app.getUserInfo().then(
      user => this.setData({src: user.avatar})
    );
  },
  onShow() {
    // 页面显示
  },
  onHide() {
    // 页面隐藏
  },
  onUnload() {
    // 页面被关闭
  },
  onTitleClick() {
    // 标题被点击
  },
  onPullDownRefresh() {
    // 页面被下拉
  },
  onReachBottom() {
    // 页面被拉到底部
  },
  onShareAppMessage() {
    // 返回自定义分享信息
    return {
      title: '校园码',
      desc: '校园二维码',
      path: 'pages/index/index',
    };
  },
});

猜你喜欢

转载自blog.csdn.net/lee576/article/details/80797325
今日推荐