尝试使用以下响应界面处理我的服务器发送回的数据。唯一的问题是response.data.data显然为空白。但是,response.data包含实际数据。
当我将鼠标悬停在response.data.data中的最后一个数据上时,它显示的类型为:(属性)ProductResponse.data:ProductDTO。
如果我修改axios.get <>()以返回一个带有response.data的Product,则该产品可以正常工作。但是我一直在使用这种接口模式,因此我尝试自己使用它。
对于专家来说可能是一种快速的方法,谢谢!
import axios from "axios";
import Product, { ProductDTO } from "@/models/Product";
interface ProductResponse {
status: number;
message: string;
data: ProductDTO;
}
// Rework to a more generic API
export abstract class ProductApi {
private static productAxios = axios.create();
static async getProduct(id: number): Promise<Product> {
let response = await this.productAxios.get<ProductResponse>(
"http://localhost:8080/api/product/" + id
);
console.log(response.data.data);
return new Product(response.data.data);
}
}
如果检查Axiosget()
函数的类型,您将看到它具有以下实现:
get<T = any, R = AxiosResponse<T>>(url: string, config?: AxiosRequestConfig): Promise<R>;
https://github.com/axios/axios/blob/master/index.d.ts#L137
因此,传递的第一个类型(T
)是数据类型,而不是响应类型。对于您的情况,您将必须通过以下方式实现它:
this.productAxios.get<Product, ProductResponse>
您的数据确实在response.data
:)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句