首页 > 解决方案 > 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;
}

标签: reactjsionic-react

解决方案


我已经弄清楚如何将 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
    }
}

希望你会发现它很有用。

谢谢!


推荐阅读