You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在OpenAPI Generator中如何将window.location.origin设为变量而非字符串

解决OpenAPI Generator生成Angular客户端时basePath动态化问题

方案一:修改OpenAPI Generator模板(一劳永逸)

OpenAPI Generator基于Mustache模板生成代码,你可以自定义模板实现basePath的动态化:

  • 找到typescript-angular模板的configuration.mustache文件(本地安装的generator通常在node_modules/@openapitools/openapi-generator-cli/templates/typescript-angular,也可从官方仓库下载对应版本的模板文件)
  • 定位到模板中定义basePath的代码段,将原本的硬编码写法:
    public basePath: string = '{{basePath}}';
    
    修改为动态获取的逻辑:
    public get basePath(): string {
      return window.location.origin + '{{basePath}}';
    }
    
    注:如果你的OpenAPI规范中basePath已设为/api,最终会自动拼接成window.location.origin + '/api',完全匹配你的需求。
  • 生成代码时通过--template-dir参数指定自定义模板目录:
    openapi-generator-cli generate -i swagger.json -g typescript-angular -o src/generated-sources/openapi --additional-properties=ngVersion=17.1.1,npmName=restClient,supportsES6=true,npmVersion=10.2.4 --template-dir=./path/to/custom-templates
    

方案二:生成后手动修改配置类(快速临时解决)

生成代码后,找到自动生成的configuration.ts文件(路径通常为src/generated-sources/openapi/configuration.ts):

  • 将硬编码的basePath替换为动态逻辑:
    // 替换前
    public basePath: string = "window.location.origin";
    // 替换后
    public get basePath(): string {
      return window.location.origin + '/api';
    }
    
    若要保留OpenAPI规范中的basePath配置,可改成:
    private readonly _basePath: string = '/api'; // 这里填生成代码中原有的basePath值
    public get basePath(): string {
      return window.location.origin + this._basePath;
    }
    

方案三:结合Angular依赖注入配置

如果想贴合Angular最佳实践、避免直接使用window,可以通过依赖注入动态配置:

  • 创建自定义模块,提供动态生成的Configuration实例:
    import { NgModule } from '@angular/core';
    import { Configuration } from './generated-sources/openapi';
    import { Location } from '@angular/common';
    
    export function provideConfiguration(location: Location): Configuration {
      const config = new Configuration();
      config.basePath = location.origin + '/api';
      return config;
    }
    
    @NgModule({
      providers: [
        { 
          provide: Configuration, 
          useFactory: provideConfiguration,
          deps: [Location]
        }
      ]
    })
    export class CustomApiModule {}
    
  • 在应用根模块中导入CustomApiModule,替代自动生成的ApiModule。

内容的提问来源于stack exchange,提问作者Georg

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.14 22:52:40