小程序api请求层封装(Loading全局配置)

前言 小程序开发,没有vue中的axios那么好使,请求层的封装需要自己来搞。

当然请求层的配置少不了loading,这里索性也就将loading做一个配置,避免以后重复造轮子

 请求封装

小程序中有封装好的请求方法:wx.request(url,method,header,success,fail,complete);方法类似于原生的ajax,

这里我们大的方面分两种,一种普通请求,一种是文件上传

普通请求又分为get请求,post请求,post请求又分为JSON格式和BODY格式因此

我们需要大致分为两步

普通请求

封装get请求和post请求为普通请求,我们需要考虑因为其post请求有两种方式所以我们需要将其作为参数来使。

// get/post请求
function fun(url, method, data, header) {
  data = data || {};
  header = header || {};
  wx.showNavigationBarLoading();
  let promise = new Promise(function (resolve, reject) {
    wx.request({
      url: baseUrl + url,
      header: header,
      data: data,
      method: method,
      success: function (res) {
        if (typeof res.data === "object") {
          if (res.data.status) {
            if (res.data.status === -200) {
              wx.showToast({
                title: "为确保能向您提供最准确的服务,请退出应用重新授权",
                icon: "none"
              });
              reject("请重新登录");
            } else if (res.data.status === -201) {
              wx.showToast({
                title: res.data.msg,
                icon: "none"
              });
              setTimeout(function () {
                wx.navigateTo({
                  url: "/pages/user/supplement/supplement"
                });
              }, 1000);
              reject(res.data.msg);
            }
          }
        }
        resolve(res.data.result);
      },
      fail: function (res) {
        // fail调用接口失败
        reject({ error: '网络错误', code: 0 });
      },
      complete: function () {
        wx.hideNavigationBarLoading();
      }
    });
  });
  return promise;
}

文件上传

upload上传和请求方法十分类似,不过不同的是请求是request上传则是upload方法。这里上传采用小程序原生的方法

function upload(url, name, filePath) {
  let header = {};
  wx.showNavigationBarLoading();
  let promise = new Promise(function (resolve, reject) {
    wx.uploadFile({
      url: baseUrl + url,
      filePath: filePath,
      name: name,
      header: header,
      success: function (res) {
        resolve(res.data.result);
      },
      fail: function() {
        reject({ error: '网络错误', code: 0 });
      },
      complete: function () {
        wx.hideNavigationBarLoading();
      }
    });
  });
  return promise;
}

我们只需要导出以上两种方法即可,不过认真看过的同学会发现baseUrl没有定义啊

这里童鞋们可以根据实际情况,分为开发,测试,生产,生产测试等情况分类,设置baseUr基本域名

这里就不做说明了。

下来我们就是最后一步了,这一步不影响使用。但是为了完美~beautiful

配置loading让交互会更加的友好

配置loading,我们不需要封装loading框,调用小程序自带的就可以,我们只需要操心的是,一个页面很多请求的时候,如何当所有请求完成时再关闭loading?

实现思路:设置一个计数器,因为这里的请求方法都要经过fun,所以说我们只需要在fun调用的时候+1,在返回失败或者成功的时候-1就可以,当等于0的时候调用关闭loading的方法就可以了,笔者简直不要太完美~

// loading配置,请求次数统计
function startLoading() {
  wx.showLoading({
    title: 'Loading...',
    icon: 'none'
  })
}
function endLoading() {
  wx.hideLoading();
}
// 声明一个对象用于存储请求个数
var needLoadingRequestCount = 0;
function showFullScreenLoading() {
  if (needLoadingRequestCount === 0) {
    startLoading();
  }
  needLoadingRequestCount++;
};
function tryHideFullScreenLoading() {
  if (needLoadingRequestCount <= 0) return;
  needLoadingRequestCount--;
  if (needLoadingRequestCount === 0) {
    endLoading();
  }
};

我们只需要在fun方法中添加showFullScreenLoading(),在返回结果的时候调用tryHideFullScreenLoading()即可实现请求层封装与loading的全局配置~完美不?

源码

下来将源码附上,有帮助的话,记得点个关注呗,待个人网站完善后将会同步至个人网站(百度搜索:狗尾草的前端博客)

const app = getApp()

const baseUrl = app.globalData.baseUrl;

// loading配置,请求次数统计
function startLoading() {
  wx.showLoading({
    title: 'Loading...',
    icon: 'none'
  })
}
function endLoading() {
  wx.hideLoading();
}
// 声明一个对象用于存储请求个数
var needLoadingRequestCount = 0;
function showFullScreenLoading() {
  if (needLoadingRequestCount === 0) {
    startLoading();
  }
  needLoadingRequestCount++;
};
function tryHideFullScreenLoading() {
  if (needLoadingRequestCount <= 0) return;
  needLoadingRequestCount--;
  if (needLoadingRequestCount === 0) {
    endLoading();
  }
};

// get/post请求
function fun(url, method, data, header) {
  data = data || {};
  header = header || {};
  wx.showNavigationBarLoading();
  showFullScreenLoading();
  let promise = new Promise(function (resolve, reject) {
    wx.request({
      url: baseUrl + url,
      header: header,
      data: data,
      method: method,
      success: function (res) {
        if (typeof res.data === "object") {
          if (res.data.status) {
            if (res.data.status === -200) {
              wx.showToast({
                title: "为确保能向您提供最准确的服务,请退出应用重新授权",
                icon: "none"
              });
              reject("请重新登录");
            } else if (res.data.status === -201) {
              wx.showToast({
                title: res.data.msg,
                icon: "none"
              });
              setTimeout(function () {
                wx.navigateTo({
                  url: "/pages/user/supplement/supplement"
                });
              }, 1000);
              reject(res.data.msg);
            }
          }
        }
        resolve(res.data.result);
        tryHideFullScreenLoading();
      },
      fail: function (res) {
        // fail调用接口失败
        reject({ error: '网络错误', code: 0 });
        tryHideFullScreenLoading();
      },
      complete: function () {
        wx.hideNavigationBarLoading();
      }
    });
  });
  return promise;
}

// 上传
function upload(url, name, filePath) {
  let header = {};
  wx.showNavigationBarLoading();
  showFullScreenLoading();
  let promise = new Promise(function (resolve, reject) {
    wx.uploadFile({
      url: baseUrl + url,
      filePath: filePath,
      name: name,
      header: header,
      success: function (res) {
        resolve(res.data.result);
        tryHideFullScreenLoading();
      },
      fail: function() {
        reject({ error: '网络错误', code: 0 });
        tryHideFullScreenLoading();
      },
      complete: function () {
        wx.hideNavigationBarLoading();
        wx.hideLoading();
      }
    });
  });
  return promise;
}

module.exports = {
  "get": function (url, data, header) {
    return fun(url, "GET", data, header);
  },
  "post": function (url, data, header) {
    return fun(url, "POST", data, header);
  },
  upload: function (url, name, filePath) {
    return upload(url, name, filePath);
  }
};

使用说明,需要在调用方法的时候传入header,为json格式的还是body格式,总结不易,你的关注是我更新的吃鸡动力~

posted @ 2019-02-22 23:25  狗尾草的博客  阅读(5775)  评论(0编辑  收藏  举报