gpt4 book ai didi

typescript - 从 axios get 请求返回数据

转载 作者:行者123 更新时间:2023-12-01 01:43:30 26 4
gpt4 key购买 nike

尝试对我的服务器发回的数据使用以下响应接口(interface)。唯一的问题是 response.data.data 显然是空白的。但是,response.data 包含实际数据。

当我将鼠标悬停在 response.data.data 中的最后一个数据上时,它显示其类型为:(属性)ProductResponse.data:ProductDTO。

如果我修改我的 axios.get<>() 以返回一个带有传递给构造函数的 response.data 的产品,一切正常。但我一直遇到这种正在使用的界面模式,所以我尝试自己使用它。

对于专家来说可能是一个快速的过程,谢谢!

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);
}
}

最佳答案

如果你检查 Axios get() 函数的类型,你会看到它有这样的实现:

  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 :)

关于typescript - 从 axios get 请求返回数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59107839/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com