小程序api请求层封装(Loading全局配置) 您所在的位置:网站首页 小程序网络请求封装 小程序api请求层封装(Loading全局配置)

小程序api请求层封装(Loading全局配置)

2024-07-12 08:11| 来源: 网络整理| 查看: 265

前言 小程序开发,没有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


【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有