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

前言 小程序开发,没有vue中的axios那么好使,请求层的封装须要本身来搞。前端

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

 请求封装

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

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

普通请求又分为get请求,post请求,post请求又分为JSON格式和BODY格式所以ajax

咱们须要大体分为两步json

普通请求

封装get请求和post请求为普通请求,咱们须要考虑由于其post请求有两种方式因此咱们须要将其做为参数来使。axios

// 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没有定义啊promise

这里童鞋们能够根据实际状况,分为开发,测试,生产,生产测试等状况分类,设置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格式,总结不易,你的关注是我更新的吃鸡动力~

相关文章
相关标签/搜索