1. 程式人生 > >小程序api請求層封裝(Loading全局配置)

小程序api請求層封裝(Loading全局配置)

因此 space 是我 posit 程序開發 web toast ace one

前言 小程序開發,沒有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格式,總結不易,你的關註是我更新的吃雞動力~

小程序api請求層封裝(Loading全局配置)