微信小程序Promise封装http之调用
1、创建http.js
1、路径:miniprogram\utils\http.js
2、相关内容:
import { config } from '../config.js'
const tips = {
1: '抱歉,出现一个错误',
3000: '数据不存',
405: 'METHOD NOT ALLOWED',
200: '提交成功',
1000: ''
}
class HTTP{
request({url,data={},method='GET'}){
return new Promise((resolve,reject)=>{
this._request(url,resolve,reject,data,method)
})
} // end request
_request(url,resolve,reject,data={},method='GET'){
wx.request({
url: config.api_local_url+url,
method: method,
data: data,
header: {
'content-type': 'application/json'
},
success: (res)=>{
const code = res.statusCode.toString()
if(code.startsWith('2')){
resolve(res.data)
let codee = res.data.code
this._show_message(codee)
}
else
{
reject()
const error_code = res.data.error_code
this._show_message(error_code)
}
},
fail: (err)=>{
reject()
this._show_message(1)
}
}) // end wx.request
}
_show_message(code){
if(!code){
code = 1
}
const tip = tips[code]
wx.showToast({
title: tip?tip:tips[1],
icon: 'noce',
duration: 2000
})
}
} // end HTTP
export {
HTTP
}
2、创建models文件
1、路径:miniprogram\models\theme.js
2、目的:调用http.js中promise实例,封装业务逻辑层类
3、继承HTTP类;
import { HTTP } from '../utils/http.js'
class ThemeModel extends HTTP {
//根据openid获取主题列表
getTheme(data){
return this.request({
url: '/duo/get',
method: 'GET',
data: data
})
}
//根据id+openid获取主题
getThemeOne(data) {
return this.request({
url: '/duo/theme',
method: 'GET',
data: data
})
}
postData(data) {
return this.request({
url: '/duo/post',
method: 'POST',
data: data
})
}
}
export {
ThemeModel
}
3、页面js文件调用models
1、Pages页面调用业务逻辑处理js文件
3.1 引用
import {ThemeModel} from '../../models/theme.js'
3.2 实例化
const themeModel = new ThemeModel()
3.3 调用themeModel方法
themeModel.postData()方法:
//事件提交
onClickRight(){
console.log(this.data.remark)
let theme = {
openid: app.globalData.openid,
title: this.data.title,
content: this.data.content,
date: this.data.date,
address: this.data.address,
checked: this.data.checked==true?1:0,
date: this.data.date,
method: this.data.method,
remark: this.data.remark
}
themeModel.postData(theme).then(res=>{
if(res.code =='200')
{
this.setData({
title: '',
content: '',
date: '',
address: '',
checked: false,
orderdate: '',
method: '货到自提',
remark: '',
})
}
})
},
showPopup(){
this.setData({
show: true
})
},