菜单 学习猿地 - LMONKEY

VIP

开通学习猿地VIP

尊享10项VIP特权 持续新增

知识通关挑战

打卡带练!告别无效练习

接私单赚外块

VIP优先接,累计金额超百万

学习猿地私房课免费学

大厂实战课仅对VIP开放

你的一对一导师

每月可免费咨询大牛30次

领取更多软件工程师实用特权

入驻
0
0

微信小程序-封装工具类

原创
05/13 14:22
阅读数 199

封装微信小程序原生方法 wx.request()

wx.request() - 微信官方文档 · 小程序
链接:https://developers.weixin.qq.com/miniprogram/dev/api/network/request/wx.request.html

在微信小程序日常开发中,我们往往需要自己封装一下工具类来简化我们的开发,例如http请求封装,弹窗封装等等
在这个项目中我封装了三个工具类:
图片.png

http.ts

export default {
  // 经验证,export外面获取不到App示例,所以封装了此方法
  getGlobalData() {
    return getApp<IAppOption>().globalData;
  },
  /**
   *  Http Request
   * @param url 
   * @param data 
   * @param method 
   * @param callcomplete 
   */
  httpRequest(
    url: string,
    data: any | undefined,
    method: "GET" | "OPTIONS" | "HEAD" | "POST" | "PUT" | "DELETE" | "TRACE" | "CONNECT" | undefined,
    header: Record<string, any> | undefined,
    callcomplete?: CallableFunction | undefined): Promise<any> {

    header = header || {}
    header['authKey'] = this.getGlobalData().accessToken

    let that = this
    return new Promise(function (resolve, reject) {
      wx.request({
        url,
        data,
        method,
        header,
        success: function (res) {
          if (res.header['authKey'] && res.header.authKey !== that.getGlobalData().accessToken) {
            that.getGlobalData().accessToken = res.header.authKey
            wx.setStorageSync("authKey", that.getGlobalData().accessToken)
          }
          if (res.statusCode == 200) {
            resolve(res.data);
          }
          else {
            console.log("wx.request() is success : 200 lost.");
            reject(res.data);
          }
        },
        fail: function (res) {
          console.log("wx.request() is fail : " + res.errMsg);
          reject(res);
        },
        complete: function (res) {
          if (callcomplete) {
            callcomplete(res)
          }
        }
      })
    })
  },

  /**
   * 客户端发起一个 HTTPS POST 请求,其中 content-type 为 multipart/form-data。
   * @param url 
   * @param filePath 
   * @param name 
   * @param formData 
   */
  uploadFile(url: string, filePath: string, name: string, formData: object) {
    return new Promise(function (resolve:any, reject) {
      wx.uploadFile({
        url,
        filePath,
        name,
        header: {
          'content-type': 'multipart/form-data'
        },
        formData,
        // 成功回调
        success(res) {
          resolve(JSON.parse(res.data));
        },
      });
    });
  },

  httpGet(url: string, param: any) {
    return this.httpRequest(this.getGlobalData().apiUrl + url, param, "GET", undefined, undefined);
  },

  httpPost(url: string, param: any) {
    return this.httpRequest(this.getGlobalData().apiUrl + url, param, "POST", undefined, undefined);
  },

  imageUpload(url: string, filePath: any, formData: object) {
    return this.uploadFile(this.getGlobalData().apiUrl + url, filePath, "file", formData);
  },
}

request.ts

import http from './http.js'

/**
 * --------------------登录相关---------------------
 */
// 获取称重列表
function getPhoneNumber(param: any) {
  return http.httpPost("/wechat/login", param);
}

// 图片上传
function imageUpload(filePath: any, formData: Object) {
  return http.imageUpload("/common/imageUpload", filePath, formData);
}

module.exports = {
  getPhoneNumber,
  imageUpload
};

util.ts

export const formatTime = (date: Date) => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()
  return (
    [year, month, day].map(formatNumber).join('/') +
    ' ' +
    [hour, minute, second].map(formatNumber).join(':')
  )
}

const formatNumber = (n: number) => {
  const s = n.toString()
  return s[1] ? s : '0' + s
}

const util = {
  /**
   * 消息提示框
   * @param title 提示信息
   * @param icon 图标 success error loading none
   * @param success 成功回调
   */
  showToast(title: string='操作成功', icon: any='success') {
    return new Promise(function(resolve, reject) {
      wx.showToast({
        title: title,
        icon: icon,
        duration: 1000
      })
    });
  },

  showModal(content: string, title: string='提示', confirmText: string='确定') {
    return new Promise(function(resolve, reject) {
      wx.showModal({
        title: title,
        content: content,
        confirmText: confirmText,
        success (res) {
          resolve(res.confirm);
        }
      })
    });
  },

  /**
   * 时间戳转日期
   * @param number 时间戳
   * @param format 格式
   */
  formatTimeTwo(number: any, format: string="Y-M-D h:m:s") {
    var formateArr = ['Y', 'M', 'D', 'h', 'm', 's'];
    var returnArr = [];
    if (number.toString().length < 13){
      number = number * 1000;
    }
    var date = new Date(number);
    returnArr.push(date.getFullYear());
    returnArr.push(formatNumber(date.getMonth() + 1));
    returnArr.push(formatNumber(date.getDate()));
    returnArr.push(formatNumber(date.getHours()));
    returnArr.push(formatNumber(date.getMinutes()));
    returnArr.push(formatNumber(date.getSeconds()));
    for (var i in returnArr) {
      format = format.replace(formateArr[i], returnArr[i]);
    }
    return format;
  }
};
module.exports = {
  util
}

app.ts

var request = require('./utils/request');
// 运用ES6语法 解构赋值
var {util} = require('./utils/util');

// app.ts
App<IAppOption>({
  request,
  util,
  globalData: {
    loginCode: '',
    phoneCode: '',
    accessToken: '',
    platformCode: '',
    apiUrl: 'http://127.0.0.1:8200/apm-api',
    resourcePath: 'D:\\Desktop\\Temp\\',
    login: null,
    isLogin: false
  },

  onLaunch() {
    this.globalData.platformCode = wx.getSystemInfoSync().platform
    this.globalData.apiUrl = this.globalData.platformCode === 'devtools' ?
      'http://127.0.0.1:8200/apm-api' :
      'https://ghy-api.shrzn.com'

    // 会话 token
    this.globalData.accessToken = wx.getStorageSync("authKey") || ""
    
    // 登录 获取 code
    wx.login({
      success: e => {
        if (e.errMsg === 'login:ok') {
          this.globalData.loginCode = e.code
        }
        console.log("wx.login()方法==>>", e)
      },
    })
  },

})

参考文章:

微信小程序request封装 https://blog.csdn.net/qq_43106047/article/details/123735673
【微信小程序原生】 封装request https://blog.csdn.net/AAAXiaoApple/article/details/124715966

发表评论

0/200
0 点赞
0 评论
收藏