问题:小程序onLoad 与 onLaunch 几乎是同时执行,那么怎么在onLoad里拿到onLaunch里异步的数据
解决办法:
在app.js中的onLaunch中调取接口获取到值
// 此处请求封装过
app.request('url',data).then(res => {
this.globalData.resData = res
// 此处判断app对象中有没有这个回调函数
if (this.CallbackFn) {
// 如果有说明,onLoad中没有拿到值,把结果当参数再传入回调中
this.CallbackFn(res);
}
}).catch(err => {
wx.showToast({
title: err.Message,
icon: 'none'
});
})
在进入的页面中的onLoad中
if (app.globalData.resData && app.globalData.resData != '') {
// 如果有值,说明接口已经返回,所以直接赋值使用
this.setData({
resData : resData
})
} else {
//如果没有,给app定义一个回调,拿到接口返回参数
app.CallbackFn= data=> {
if (data!= '') {
that.setData({
resData: data
})
}
}
}