reactjs - Ionic + React 如何返回 Promiseapi调用后?
问题描述
我想将 API 响应 JSON 返回到模型类中。
示例代码如下:
const authenticateUserAsync = async (username: string, password: string) : Promise<UserModel> => {
const loginData = {
"Username": username,
"Password": password
}
const api = axios.create({
baseURL: "https://www.something.com/api/services"
})
const resp = await api.post("/ValidateUserPost", loginData)
if(resp.data != null && resp.data.userId != null && resp.data.userId > 0){
//How to convert the JSON Response to Model Class
return resp.data.map((user: UserModel) => {UserId: user.userId, FirstName: user.FirstName })
}
else
return NULL User Model
};
我要返回的模型类如下所示:
export interface UserModel {
UserId: Number;
CustomerId: number;
FirstName:string;
LastName:string;
}
解决方案
我已经弄清楚如何将 API 响应数据设置到我的模型类中。
示例代码如下
const authenticateUserAsync = async (username: string, password: string) : Promise<UserModel> => {
const loginData = {
"Username": username,
"Password": password
}
const api = axios.create({ baseURL: "https://www.something.com/api/services"})
const resp = await api.post("/ValidateUserPost", loginData)
//Check if the data is not null. API response could be obtained into .data property. And, the data needs to be set into model class properties
if(resp.data != null && resp.data.userId != null && resp.data.userId > 0){
return {
UserId: resp.data.userId ,
FirstName: resp.data.firstName,
LastName: resp.data.lastName,
CustomerId: resp.data.customerId }
} else return null
}
}
希望你会发现它很有用。
谢谢!
推荐阅读
- javascript - 使用javascript检索复选框标签文本
- node.js - Graphql 调用:网络错误 - 无法仅获取长任务
- python - 如何从csv文件python中跳过非数字行
- python-3.x - ValueError:发现时间倒置
- html - Css不显示为编码
- clickhouse - 使用 ClickHouse 实现最终聚合值(不是状态)
- google-tag-manager - 优化谷歌标签
- css - 如何修改这个 Bootstrap Sass mixin 以逐步遍历不同的元素?
- kerberos - 使用 Kerberos 进行 RDP
- java - Junit 平台 v.5.8.1 java.lang.NoSuchMethodError: org.junit.platform.commons.util.AnnotationUtils.findAnnotation 出现错误