小程序開發(fā)中都會調(diào)用后端工程師開發(fā)的API,小程序的開發(fā)文檔提供了相對實用的APIwx.request(),但是在開發(fā)的過程中,又遇到了一些問題,在小程序的項目開發(fā)時,調(diào)用的API不止一個,同一個API調(diào)用不止一次。同時,對于調(diào)用的API的管理也十分復(fù)雜,這樣的背景下,對wx.request()方法的封裝變得尤為重要。
本文的解決思路為:將API的路徑和方法放在一個文件里面方便管理;封裝小程序的request方法,并返回promise處理(ES6)。
一、units文件夾中新建request.js文件
// utils/request.js
//封裝request
let apiRequest = (url, method, data, header) => { //接收所需要的參數(shù),如果不夠還可以自己自定義參數(shù)
let promise = new Promise(function (resolve, reject) {
wx.showNavigationBarLoading() //在標(biāo)題欄中顯示加載
wx.request({
url: url,
data: data ? data : null,
method: method,
header: header ? header : { 'content-type': 'application/x-www-form-urlencoded' },
complete: function () {
wx.hideNavigationBarLoading(); //完成停止加載
wx.stopPullDownRefresh(); //停止下拉刷新
},
success: function (res) {
//接口調(diào)用成功
resolve(res.data); //根據(jù)業(yè)務(wù)需要resolve接口返回的json的數(shù)據(jù)
},
fail: function (res) {
wx.showModal({
showCancel: false,
confirmColor: '#1d8f59',
content: '數(shù)據(jù)加載失敗,請檢查您的網(wǎng)絡(luò),點擊確定重新加載數(shù)據(jù)!',
success: function (res) {
if (res.confirm) {
apiRequest(url, method, data, header);
}
}
});
wx.hideLoading();
}
})
});
return promise; //注意,這里返回的是promise對象
}
export default apiRequest;
二、units文件夾中新建api.js文件
import apiRequest from './request.js';
const HOST = 'http://www.xx.com';
const API_LIST = {
all: {
method: 'POST',
url: '/e/extend/api/type.php'
},
}
/*
多參數(shù)合并
*/
function MyHttp(defaultParams, API_LIST) {
let _build_url = HOST;
let resource = {};
for (let actionName in API_LIST) {
let _config = API_LIST[actionName];
resource[actionName] = (pdata) => {
let _params_data = pdata;
return apiRequest(_build_url + _config.url, _config.method, _params_data, {
'content-type': 'application/x-www-form-urlencoded;charset=utf-8;Authorization;'
});
}
}
return resource;
}
const Api = new MyHttp({}, API_LIST);
export default Api;
三、業(yè)務(wù)中使用
import Api from '/../../utils/api.js';
.
.
.
getAll() {
Api.all({ id: 1 }).then(res => {
console.log(res);
})
}
通過對小程序網(wǎng)絡(luò)請求方法的二次封裝,使得我們的代碼看上去更加的簡潔,在接口的管理上也相對的便利,比如在后端修改API的路徑和方法時,只需要在api.js文件中修改相應(yīng)的API即可,也免去了修改時忽略了更多調(diào)用的麻煩。同時,也提高了代碼的復(fù)用性,一勞永逸。