在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}}';
注:如果你的OpenAPI规范中basePath已设为public get basePath(): string { return window.location.origin + '{{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替换为动态逻辑:
若要保留OpenAPI规范中的basePath配置,可改成:// 替换前 public basePath: string = "window.location.origin"; // 替换后 public get basePath(): string { return window.location.origin + '/api'; }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
相关产品推荐
相关产品推荐

