typescript - 如何使用 OpenAPITools 代码生成器生成的 Axios API 客户端?
问题描述
我正在使用 Swagger/OpenAPI Codegen 为我的 Vue 应用程序中的 Fetch 客户端生成 API 客户端,并希望改用 Axios。我首先使用OpenAPITools typescript -axios 代码生成器:
java -jar .\openapi-generator-cli.jar generate -i http://localhost:5000/swagger/v1/swagger.json -g typescript-axios -o app\api
然后我尝试将输入的响应分配给相同类型的局部变量:
@Component
export default class Themes extends Vue {
private themesApi!: ThemesApi;
private themes: Theme[];
constructor() {
super();
this.themes = [];
}
private async mounted() {
const apiConfig: Configuration = {
basePath: config.API_URL,
};
this.themesApi = new ThemesApi(apiConfig);
}
private async getThemes() {
this.themes = await this.themesApi.getThemes();
}
}
但是,这引发了以下 TypeScript 错误:
> 139:5 Type 'AxiosResponse<Theme[]>' is missing the following
> properties from type 'Theme[]': length, pop, push, concat, and 28
> more.
> 137 |
> 138 | private async getThemes() {
> > 139 | this.themes = await this.themesApi.getThemes();
> | ^
那么为什么会引发这个错误呢?
解决方案
看看 Axios 的类型,特别是AxiosResponse
:https ://github.com/axios/axios/blob/master/index.d.ts#L70
您会看到它接受一个泛型,在您的情况下Theme
,它可以在data
属性下访问。因此,您需要使用以下内容来获取您的价值:
private async getThemes() {
const response = await this.themesApi.getThemes();
this.themes = response.data;
}
推荐阅读
- javascript - React Material-UI最简单的Hello Wold测试中的无效钩子调用错误
- encryption - 这种双挂锁类比与公私钥加密+签名之间是否有任何功能差异?
- java - JLabel上的透明背景GIF表现奇怪
- python - Performing for loop in pandas
- c# - System.ArgumentNullException:值不能为空 ASP.NET MVC5
- r - R。如何对名称中带有 () 括号的行进行子集化?
- visual-c++ - 与结构成员变量关联的对话框控件
- javascript - Highcharts - PieChart 在调用 this.setState 的点击事件上刷新
- c++ - 试图转换 wxVector 的一个组件
这是 wxString 到 wxStringArray 但程序不想 - python - 遍历 pandas 中的列,同时对每列应用不同的函数