Angular 13跨域部署同构建包切换API地址失败求助
同一构建包跨环境部署时API地址未自动切换问题
功能需求
为DEV环境构建应用包并部署到DEV域名,无需重新构建即可将同一部署包发布到QC环境,自动使用环境文件中对应的QC API地址。
已实施步骤
- 步骤1:创建两个环境文件,分别对应DEV和QC的API地址。
- 步骤2:编写
EnvironmentService.ts文件,代码如下:
export class EnvironmentService { private currentEnvironment: any; constructor() { // Determine the current domain or environment and load the appropriate config const currentDomain = window.location.hostname; if (currentDomain === 'https://devums.sahibandhu.com') { this.currentEnvironment = environmentDev.baseUrlDev; } else if (currentDomain === 'https://qcums.sahibandhu.com') { this.currentEnvironment = environmentQc.baseUrlDev; } else if (currentDomain === 'https://uatums.sahibandhu.com') { this.currentEnvironment = environmentUat.baseUrlDev; } else if (currentDomain === 'https://ums.sahibandhu.com') { this.currentEnvironment = environmentProd.baseUrlDev; } else { // Default to a specific environment if none matches this.currentEnvironment = environmentDev.baseUrlDev; console.log(this.currentEnvironment); } } getConfig() { return this.currentEnvironment; } }
- 步骤3:在
appmodule.ts中注册该服务,代码如下:
export function initializeApp(environmentService: EnvironmentService) { return () => environmentService.getConfig(); }
- 步骤4:在API调用时获取当前环境变量。
问题现象与推测
预期部署DEV构建包到QC环境时,会自动识别qcums.sahibandhu.com域名并切换API地址,但实际DEV和QC环境均使用DEV的API地址,推测是因为构建基于DEV环境导致。
内容的提问来源于stack exchange,提问作者Akshita Tyagi
相关产品推荐
相关产品推荐

