HarmonyOS 鸿蒙Next怎么将网络请求返回的response.result转换为自定义的数据类对象,且自定义数据类中方法不丢失?
HarmonyOS 鸿蒙Next怎么将网络请求返回的response.result转换为自定义的数据类对象,且自定义数据类中方法不丢失?
let httpRequest = this.createHttpClient()
try {
let response:http.HttpResponse = await httpRequest.request(
this.baseUrl + this.suffixUrl,
options
)
let result = response.result
let zyCommonResponse:ZyCommonResponse<T> | null;
if(typeof result === ‘string’) {
zyCommonResponse = JSON.parse(result) as ZyCommonResponse<T>;
} else if(typeof result === ‘object’) {
zyCommonResponse = result as ZyCommonResponse<T>;
} else {
zyCommonResponse = result as ZyCommonResponse<T>;
}
return zyCommonResponse
} catch (e) {
// 请求错误拦截
throw e as Error
} finally {
httpRequest.destroy()
}
更多关于HarmonyOS 鸿蒙Next怎么将网络请求返回的response.result转换为自定义的数据类对象,且自定义数据类中方法不丢失?的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html
class ZyCommonResponse<T> {
data: T;
// 其他属性...
// 构造函数
constructor(data: T) {
this.data = data;
}
// 自定义方法
someMethod() {
// 实现...
}
// 静态方法
static fromResponse(responseData: any): ZyCommonResponse<any> {
if (typeof responseData === 'string') {
responseData = JSON.parse(responseData);
}
return new ZyCommonResponse(responseData.data as T); //响应数据
}
}
// 使用
let zyCommonResponse = ZyCommonResponse.fromResponse(response.result);
zyCommonResponse.someMethod();
更多关于HarmonyOS 鸿蒙Next怎么将网络请求返回的response.result转换为自定义的数据类对象,且自定义数据类中方法不丢失?的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html