1. 程式人生 > >微信小程序之封裝http請求

微信小程序之封裝http請求

下拉 user search log onload con dos port ole

下面將封裝http請求服務部分的服務以及引用部分

// 本服務用於封裝請求
// 返回的是一個promisepromise

var sendRrquest = function (url, method, data, header) {
    var promise = new Promise(function (resolve, reject) {
        wx.request({
            url: url, 
            data: data,
            method: method,
            header: header,
            success: resolve,
            fail: reject
        })
    });
    
return promise; }; module.exports.sendRrquest = sendRrquest

在utils文件中創建文件requestService.js文件

下邊是在page.js文件中引用部分代碼

// 界面一般通過使用Page函數註冊一個界面,接收一個Object對象,該對象指定了初始化數據/生命周期函數函數/事件處理函數
// data 存放頁面初始化數據數據,類似angular的的$scope
// onLoad 生命周期函數 監聽頁面加載
// onReady 生命周期函數 監聽頁面首次渲染完成完成
// onShow  生命周期函數 監聽界面顯示
// onHide 生命周期函數 監聽界面隱藏
// onUnload 生命周期函數 監聽頁面卸載 // onPullDownRefresh 頁面相關事件 監聽用戶下拉事件 // onReachBottom 頁面上拉到達底部觸發的事件 // onShareAppmessage 點擊左上方分享事件 var testService = require(‘../../utils/testService.js‘) var request = require(‘../../utils/requestService.js‘) Page({ data:{ test:‘123‘, positionlist:[] }, onLoad:
function(){ }, onReady: function () { var that = this; testService.test(‘a‘); testService.agerntest(‘a‘); var url = ‘https://webapi.tianjihr.com/position/searcher?sort=-refresh_time&offset=10&limit=10‘; request.sendRrquest(url, ‘GET‘, {}, {}) .then(function (response) { that.setData({ positionlist:response.data.list }); console.log(response); }, function (error) { console.log(error); }); }, onPullDownRefresh: function () { }, onShareAppMessage: function () { // 微信分享需要的配置參數 return { title: ‘自定義分享標題‘, desc: ‘自定義分享描述‘, path: ‘/page/user?id=123‘ } // console.log(1); } });

上邊的代碼和js代碼有不同的代碼需要註意

1.異步處理方式改變

原有方式是:

var promise = new Promise();
promise.resolve(‘成功‘);
promise.reject(‘失敗‘);
return promise;

現有的方式:

return new Promise(function (resolve, reject) {
    resolve(‘成功‘);
    reject(‘失敗‘);
})

2.在promise成功或者失敗的回調中不能直接賦值,如:

var that = this;
test()
.then(function(){
   that.data.test=‘‘;
},function(){

})

需要使用如下方式:

var that = this;
test()
.then(function(){
   that.setDatat={
       test:123
   };
},function(){

})

微信小程序request請求封裝

 1 var app = getApp();
 3 
 4 function request(url,postData,doSuccess,doFail,doComplete){
 5 
 6    var host = getApp().conf.host;
 8 
 9     wx.request({
10 
11       url: host+url,
13 
14       data:postData,
15 
16       method: ‘POST‘,
17 
18       success: function(res){
19 
20        if(typeof doSuccess == "function"){
22 
23          doSuccess(res);
24 
25        }
26 
27       },
28 
29       fail: function() {
31 
32        if(typeof doFail == "function"){
34 
35          doFail();
36 
37        }
38 
39       },
40 
41       complete: function(){
43 
44        if(typeof doComplete == "function"){
46 
47          doComplete();
48   
49        }
51       }
52 
53    });
55  }
57 }60 
61 module.exports.request = request;

微信小程序之封裝http請求