HarmonyOS 鸿蒙Next怎么将网络请求返回的response.result转换为自定义的数据类对象,且自定义数据类中方法不丢失?
HarmonyOS 鸿蒙Next怎么将网络请求返回的response.result转换为自定义的数据类对象,且自定义数据类中方法不丢失?
目前代码如下,但ZyCommonResponse和范型T中都会丢失方法:
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()
}
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()
}
2 回复
大致思路如下:
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();