下面将封装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;