【问题标题】:How to use Axios API client generated by OpenAPITools code generator?如何使用 OpenAPITools 代码生成器生成的 Axios API 客户端?
【发布时间】:2019-08-08 03:58:13
【问题描述】:

我正在使用 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();
>         |     ^

局部变量的类型相同:

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

【问题讨论】:

标签: typescript axios


【解决方案1】:

查看 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;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-23
    • 2010-10-09
    • 2022-06-21
    • 1970-01-01
    • 2015-03-04
    • 1970-01-01
    相关资源
    最近更新 更多