Harmonyos5应用开发实战——业务功能工具函数封装
文章内容概要
本文聚焦于HarmonyOS 5应用开发中一系列业务功能工具函数的封装。这些工具函数涵盖了用户登录登出、店铺信息获取、优惠券操作、购物车管理、订单处理、商品信息查询等多个方面,为应用的各个业务模块提供了便捷的调用接口,有效提升了开发效率和代码的可维护性。
核心功能介绍
1. 网络请求封装
为了方便与后端进行数据交互,封装了多个网络请求工具函数,如获取店铺信息、用户信息、优惠券列表等。这些函数基于 HttpRequestApi 模块,通过 Promise 处理异步请求结果。
export function getStoreInfoUtil(storeId: string): Promise<GetStoreInfoResp> {
return new Promise((resolve, reject) => {
HttpRequestApi.getStoreInfo(storeId)
.then((resp: GetStoreInfoResp) => {
if (resp.store) {
console.info(`getStoreInfo resp:${JSON.stringify(resp)}.`);
resolve(resp)
} else {
console.error(`getStoreInfo error: ${JSON.stringify(resp)}.`);
reject(resp)
}
})
.catch((e: BusinessError) => {
console.error(`getStoreInfo error: ${JSON.stringify(e)}.`);
reject(e)
})
})
}
2. 购物车管理
提供了购物车相关的操作函数,包括添加商品到购物车、更新购物车商品数量、清空购物车等。每次操作后会调用 getMyCarUtil 函数更新购物车数据。
export function addCarUtil(good: Good, num: number = 1): Promise<number> {
return new Promise((resolve, reject) => {
HttpRequestApi.addCar(good, num).then((resp: number) => {
if (resp) {
console.info(`addCar resp:${JSON.stringify(resp)}.`);
getMyCarUtil()
resolve(resp)
} else {
console.error(`addCar error: ${JSON.stringify(resp)}.`);
reject(resp)
}
})
.catch((e: BusinessError) => {
console.error(`addCar error: ${JSON.stringify(e)}.`);
reject(e)
})
})
}