小程序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格式,總結不易,你的關注是我更新的吃雞動力~

相關文章
相關標籤/搜索