项目中遇到这样一个问题就是需要登录之后存一个id然后发现第一次进来的时候登录方法在index的方法后执行 拿不到想要的值

解决办法

1.就是可以加一个启动页 做个缓冲

2.用promise

直接看代码实例吧

这是我的app.js

//app.jsApp({  onLaunch: function(options) {    // 小程序启动逻辑    // 1. 登录    // 2. 查看用户是否授权    // 3. 获取用户的设备信息    var thisPage = this;    console.log(options);    if (options.path !== "pages/index/index") {      console.log(1111);      this.globalData.destPath = options.path;    }    wx.showLoading({      title: "登录中",      mask: true    });  },  // login  getLogin() {    var that = this;    return new Promise(function(resolve, reject) {      // 登录      wx.login({        success: res = {          console.log(res);          //todo 发送 res.code 到后台换取 openId, sessionKey, unionId          wx.request({            url: that.globalData.serverHost + "/sa/login",            data: res.code,            method: "post",            success: function(res) {              console.log(res);              wx.hideLoading();              if (res.data.code === 0) {                resolve(res);              } else {                wx.showToast({                  title: "登录失败,请重新启动小程序",                  mask: true                });                reject('error');              }            },            fail: function(data) {              wx.hideLoading();              console.log(data);            }          });        }      });    });  },  globalData: {    userInfo: null,    authorized: false,    systemInfo: null,    systemInfoStr: null,    sessionToken: "",  }});

重点再这

千万别漏掉成功里的resolve(res);不然没办法执行then方法

这是index。js

 onLoad: function() {    var that =this;    app.getLogin().then(function (res) {      console.log(res)      that.attached();//初始化页面数据    })  },

 

TAG标签: 微信小程序onload事件

http://www.xiaochengxub.com/read-105170.html