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

部署到测试环境时ngx-translate请求en.json的URL错误

解决ngx-translate加载i18n文件时URL指向错误的问题

1. 配置环境变量

在Angular的环境配置文件中分别定义本地和测试环境的i18n文件基础URL:

// src/environments/environment.test.ts(测试环境)
export const environment = {
  production: false,
  i18nBaseUrl: 'https://test.your-domain.com/assets/i18n/'
};

// src/environments/environment.ts(本地开发)
export const environment = {
  production: false,
  i18nBaseUrl: '/assets/i18n/'
};

2. 自定义HttpLoaderFactory

修改app.module.ts中的翻译加载器配置,用环境变量指定的URL加载翻译文件:

import { HttpClient } from '@angular/common/http';
import { TranslateHttpLoader } from '@ngx-translate/http-loader';
import { environment } from '../environments/environment';

export function HttpLoaderFactory(http: HttpClient) {
  return new TranslateHttpLoader(http, environment.i18nBaseUrl, '.json');
}

@NgModule({
  imports: [
    HttpClientModule,
    TranslateModule.forRoot({
      loader: {
        provide: TranslateLoader,
        useFactory: HttpLoaderFactory,
        deps: [HttpClient]
      }
    })
  ]
})
export class AppModule { }

3. 打包时指定测试环境

执行打包命令时指定使用测试环境配置,确保打包后的代码用测试环境的URL:

ng build --configuration=test

额外排查点

  • 确认angular.json中已正确配置测试环境的文件替换规则:
"configurations": {
  "test": {
    "fileReplacements": [
      {
        "replace": "src/environments/environment.ts",
        "with": "src/environments/environment.test.ts"
      }
    ]
  }
}
  • 如果测试环境的i18n文件部署在特定路径,需同步调整i18nBaseUrl为对应路径,保证能访问到en.json。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 05:42:09