收藏
评论

需要登录的页面加一个判断利用Promise

我这边给你写一个简单的案例吧。

文件一 app.js

//app.js
App({
  onLaunch: function () {
  },
    cache: {
        getuserid: function () {
            return wx.getStorageSync('loginuserid');
        }
    },
    wx:{
        request_post: function (url, data) {
            return new Promise(function (resolve, reject) {
                wx.request({
                    url: url,
                    data: data,
                    method: 'POST',
                    header: { "Content-Type""application/x-www-form-urlencoded" },
                    success: function (res) {
                        resolve(res)
                    },
                    fail: function (err) {
                        reject(err)
                    }
                });
            });
        }
    }
})


文件二 helper.js

//utils/helper.js
var app = getApp();
function weixinauth() {
    return new Promise(function (resolve, reject) {
        if (app.cache.getuserid() > 0) {
            resolve("无需登录")
        else {
            wx.login({
                success: function (res) {
                    if (!res.code)
                        return;
                    //##################################
                    app.wx.request_post('https://api.xxx.com/api/weixin/auth', {
                        code: res.code,
                    }).then(function (res) {
                        wx.setStorageSync("loginuserid", res.data.userid);
                        resolve(res.data)
                    }).catch(function (err) {
                        reject(err.data)
                    })
                    //##################################
                }
            });
        }
        //##################################
    });
}
module.exports.weixinauth = weixinauth;


文件三 index.js-------就是需要登录页面的调用

// pages/index.js
var helper = require("../utils/helper.js")
var that;
var app = getApp();
Page({
  data: {
   
  },
    onLoad: function (options) {
        that = this;
        helper.weixinauth().then(function (resdata) {
            console.log("resdata");
            that.GoLoad();
        }).catch(function (errdata) {
            console.log("errdata");
        })
  },
    GoLoad:function(){
        //这里写加载页面的方法
        var userid = app.cache.getuserid();
        console.log("GoLoad");
    }
})



收藏

5 个评论

  • 神经蛙
    神经蛙
    2018-05-10

    问题见图片里的文字


    2018-05-10
    赞同 1
    回复
  • 一吻倾城ʚ 🦌 ɞ
    一吻倾城ʚ 🦌 ɞ
    2018-05-11

    谢谢分享

    2018-05-11
    赞同
    回复
  • Jake
    Jake
    2018-05-10

    对的

    2018-05-10
    赞同
    回复
  • 神经蛙
    神经蛙
    2018-05-10

    GoLoad里面,加载数据吗

    2018-05-10
    赞同
    回复
  • Jake
    Jake
    2018-05-10

    我不清楚,你具体说的什么意思?可以详细说明一下吗?

    2018-05-10
    赞同
    回复
登录 后发表内容