通常在用户进入小程序的时候,需要拿到用户的身份证明(token),以及用户授权状态(auth)以及小程序配置信息(config),未授权就是游客,已授权就是注册用户,注册用户有自己的用户信息(userinfo);比如在某一篇文章中,进行评论,收藏需要先判断用户的授权状态,已经授权才可以进行操作,未授权则提示授权;这样的话,我们在进入这个页面之前就必须获取到用户的token,cinfig,以及auth,
load: function () {
var that = this;
return new Promise(function (resolve, reject) {
Promise.all([that.login(), that.config()]).then(function ([token, config]) {
that.auth().then(Authorize => {
if (Authorize) {
that.user();
}
resolve()
})
})
})
},
user: function (token) {
var that = this;
return new Promise(function (resolve, reject) {
wx.request({
url: that.baseUrl + 'tt/user',
header: {
'token': wx.getStorageSync('token'),
'cld.stats.page_entry': that.globalData.scene,
'version': that.globalData.version
},
methos: 'GET',
success: function (res) {
if (res.statusCode == 200) {
wx.setStorageSync("user", res.data)
resolve(res.data);
}
},
fail: function () {
console.log('授权失败,请重试');
that.globalData.Authorize = false;
wx.setStorageSync('Authorize', false);
}
})
})
},
这里获取config不需要token,但是页面需要一些config信息。所以我就用了promis.all方法封装了load()函数,拿到token以后放到缓存,调用auth 方法获取授权状态如果为true,则调用user方法获取用户信息。false则不调用;
在正常从列表页面进入详情的时候贴token,authc,onfig在列表页加载的时候已经获取到,但是如果分享出去的直接打开是没有这些信息的的,所以我会在从列表进入详情的路径中携带flag参数,分享出去的是没有的。所以我们在分享的进入新闻详情页面onlooad 的时候需要进行判断
onLoad: function (options) {
let that = this;
this.setData({
id: options.scene
})
if (options.flag) {
api.request(api.Url.newsDetails + id, 'GET', {}).then(res => {
console.log("res", res);
}).catch(res => {
}).finally(() => {
})
} else {
app.load().then(() => {
api.request(api.Url.newsDetails + id, 'GET', {}).then(res => {
console.log("res", res);
}).catch(res => {
}).finally(() => {
})
})
}
},
这样的话就能避免分享转发出去的详情页面拿不到token,config的情况就开始加载