首页 > 解决方案 > 如何使用 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();
>         |     ^

局部变量的类型相同: 显示局部变量的屏幕截图具有相同的类型。

那么为什么会引发这个错误呢?

标签: typescriptaxios

解决方案


看看 Axios 的类型,特别是AxiosResponsehttps ://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;
}

推荐阅读