在小程序中,我们一般在onLaunch中发起登录请求,由于是请求是异步的,在onLoad之后才执行完登录请求,如果在onLoad中需要使用请求后的数据,会发现取不到值,以下是一些解决方式,可以按自己所需使用。
- 使用回调函数
// app.js
onLaunch () {
wx.login({
success: result => {
wx.request({
url: 'test.php' // 示例
data: {...},
success: res => {
this.globalData.openId = res.data.openId
// 回调
if (this.loginCallback) this.loginCallback(res.data)
},
fail: err => {
// 需要的话请求失败处也可以使用回调
}
})
}
})
}
// page.js
onLoad () {
const app = getApp()
if (app.globalData.openId) {
// do something
} else {
app.loginCallback = (data) => {
// do something
}
}
}
- 使用Promise
// app.js
App({
initLogin () {
return new Promise((resolve, reject) => {
wx.login({
success: result => {
wx.request({
url: 'test.php' // 示例
data: {...},
success: res => {
resolve(res.data)
},
fail: err => {
reject('error')
}
})
}
})
})
}
})
// page.js
onLoad () {
const app = getApp()
app.initLogin().then(res => {
// do something
}).catch(err => {})
}
- 使用Object.defineProperty监听
// app.js
watch (method) {
let obj = this.globalData
// 这里监听 openId
Object.defineProperty(obj, "openId", {
configurable: true,
enumerable: true,
set: function (value) {
method(value) // 触发页面回调函数
}
})
},
onLaunch () {
wx.login({
success: result => {
wx.request({
url: 'test.php' // 示例
data: {...},
success: res => {
this.globalData.openId = res.data.openId
}
})
}
})
}
// page.js
onLoad () {
const app = getApp()
app.watch(this.watchBack)
}
watchBack (openId) {
if (openId) {
// do something
}
}
- 使用getCurrentPages(官方不建议这么使用,因为可能此时 page 还没有生成)
// app.js
onLaunch () {
wx.login({
success: result => {
wx.request({
url: 'test.php' // 示例
data: {...},
success: res => {
const currentPage = wx.getCurrentPages()[0]
// 触发当前页的init方法
currentPage.init(res.data)
}
})
}
})
}
// page.js
init (data) {
// do somethine
}
- reLaunch重载页面
// app.js
onLaunch () {
wx.login({
success: result => {
wx.request({
url: 'test.php' // 示例
data: {...},
success: res => {
// 请求结果存到了storage里,再跳到页面可以获取到storage里的数据
wx.reLaunch({
url: '/pages/n-index/n-index',
})
}
})
}
})
}
- 设置启动页
- …