前言
在开发前端项目中,为了统一管理接口,方面后期维护,我们通常会把所有接口放在一个或几个js/ts文件中。这样做的好处是方便维护,并且在后端数据格式统一的情况下,方便我们做报错,成功的反馈给用户。
如何封装
那么如何封装呢,这里以ts文件为例,来封装api,使用js的小伙伴直接将类型去掉即可。
首先,我们需要封装一个统一的数据加载时的函数
对下面代码块进行几点说明
- 在ts语言中,我们需要对数据类型进行定义,所以此处定义函数function getDatas<T>,这里的T代表泛型,使用这个函数的时候传入对于的数据类型,他会return new Promise<T> ,也就是resolve一个这个类型的结果,这样当我们在使用时,类型才不会不匹配
- 这里getDatas传入的是一个http请求,定义它的他的类型为Promise类型的函数, 也就是这样 http : () => Promise<any>
- 我这里是uniapp开发,和不会uniapp的小伙伴说一下
这个是uniapp自带的一个弹出加载中的界面
uni.showLoading({
title: "加载中"
})
在数据获取成功后关闭加载中界面,我这里后台返回的code就代表是否成功,为200的时候,resolve(res)返回成功结果,其他情况调用uni.showToast,提示用户获取数据失败
uni.hideLoading()
// 统一封装请求
function getDatas<T>(http : () => Promise<any>) {
return new Promise<T>((resolve) => {
//弹出加载中界面
uni.showLoading({
title: "加载中"
})
http().then((res : any) => {
// 当数据已经拿到 关闭加载中界面
uni.hideLoading()
//钱包数据判断:res.userCouponList res.userId 用户token判断 res.userIntegral:用户签到 res.currentPwd:开锁密码
if (res.code == 200) {
resolve(res)
} else {
// 其他情况均为获取数据失败 提示错误
uni.showToast({
icon: "error",
title: "数据获取失败"
})
}
}).catch((err : any) => {
// 请求失败 提示
uni.showToast({
icon: "error",
title: "数据获取失败"
})
console.log("err", err)
})
});
}
还可以加上一个判断,当首次请求失败的时候,我们不直接弹出错误消息,再试两次,3次请求均失败,再报错,如下:
function getDatas<T>(http : () => Promise<any>) : Promise<T> {
let attempts = 0; // 初始化尝试次数
const executeRequest = () : Promise<T> => {
uni.showLoading({
title: '加载中'
});
return http().then((res : any) => {
uni.hideLoading();
// 根据你的条件,添加你所需要的判断逻辑
if(res.code == 500){
attempts++;
if (attempts < 3) {
// 在3次之内失败,尝试重新发起请求
return executeRequest();
}
uni.showToast({
icon: "error",
title: "数据获取失败"
})
}
if (res.code == 200 || res.code == "0" || res.status == 0) {
return res;
} else if (res.length >= 0) {
return res;
} else {
uni.showToast({
icon: "error",
title: "数据获取失败"
})
}
}).catch((err : any) => {
console.log(err)
uni.hideLoading();
attempts++;
if (attempts < 3) {
// 在3次之内失败,尝试重新发起2次请求 不行再报错
return executeRequest();
} else {
// 如果超过两次,则显示错误
uni.showToast({
icon: "error",
title: "网络错误"
});
}
});
};
return executeRequest();
}
2.封装请求
封装方法很简单,只需要传入两个参数,下面是一个示例
- 第一个参数就是你期望返回的数据类型,比如我这里期望返回的数据类是allApi.allAddress[],意思是,一个里面全是allApi.allAddress类型的数组。
- 第二个参数就是传入形参,就是我们上面定义的http请求,用你的请求替换掉axios就可以
替换: axios({
url: "address-info/getAllAddressInfoByUserId",
method: "get",
params: {
userId: token.userId
}
})
// 获取用户地址
export let getAllAddress = () => {
return getDatas<allApi.allAddress[]>(() => {
return axios({
url: "address-info/getAllAddressInfoByUserId",
method: "get",
params: {
userId: token.userId
}
})
})
};
在组件中使用
上面两步都做完就可以在组件中使用了
1、首先是我们需要从api文件中import对应的函数
import { getAllAddress } from "@/api/api"
2、使用
// 获取当前用户地址簿
async function getAllAddressInfoByUserId() { //因为返回的是一个Promise,所以使用async来异步
let res = await getAllAddress() //等待返回结果后在进行下一步
allAddress.value = res //将返回结果存入变量
}
在进行这系列封装后,我们就不用在每一个页面获取数据的时候,都提示加载中,在数据获取失败后提示数据获取失败,实现了代码复用,减少了一部分代码量
当然,有一些接口我们的成功失败要做的操作是不一样的,比如登录,我们要返回登录成功,登录失败,或者其他情况,那么我们可以这样
// 验证码登录
export let SMSControllerLogin = async (phoneNumber : string, code : string) => {
let data = axios({
url: "SMSController/login",
method: "get",
params: {
phoneNumber: phoneNumber,
code: code
}
})
return data;
}
使用方法
// 验证码登录
async function captchaLogin() {
let res = await SMSControllerLogin(phoneNumber.value, code.value)
if (res.code == "200") {
console.log("登录成功", res)
} else if (res.code == "404") {
// 验证码过期
uni.showToast({
icon: "error",
title: '验证码过期',
duration: 2000
});
} else {
// 验证码过期
toast.value.show({ message: "登录失败,请重试", position: "top", overlay: false })
}
}
就是这样了,希望可以帮到大家。如果有什么问题欢迎评论指出。