ngx translate angular 7 如何翻译来自 differents API 的动态数据

ngx translate angular 7 how to translate dynamic data comes from differents API's

我遇到了 ngx-translate 的问题!那是我有 2 个不同语言的 sperate API,例如类似于 http://example.com/apihttp://example.com/fr/api/

现在在 ngx-translate 中我必须使用 en/fr.json 文件来翻译我的 angular 应用程序!正如我从文档中看到的那样!

但现在我需要使用来自两个 API 的数据!已经在服务器上翻译了!

http://example.com/api

http://example.com/fr/api/

所以我的问题是我该怎么做?!还要继续使用 json files,因为我的应用程序中有一些静态词,例如 the application menu

如果有任何其他选择,请不要犹豫告诉!

假设:

  • 只有 2 个可能的语言选项:["en","fr"]
  • 翻译文件不是从本地化的 API 中提取的。相反,它们位于您项目的 assets 文件夹中。
  • 通过 ngx-translate 更改语言时,无需重新获取数据

您可以创建 构建 正确 API 端点的服务,如下所示:

@Injectable()
export class EnpointLocalizer {
  private readonly tokenMap = {'en': '/', '/fr/'}
  constructor(private readonly translate: TranslateService){}

  localizeJoin(sections: string[]){
   const {currentLang} = this.translate;
   return sections.join(this.tokenMap[currentLang] || '/'); 
  }
}

然后你可以在需要的地方注入它并按如下方式使用它:

@Injectable()
export class FooService {
 private endpoint = ["http://example.com","api"];

 constructor(private http: HttpClient, private localizer: EnpointLocalizer){}

 fetch(){
   return this.http.get(this.localizer.localizeJoin(this.endpoint),...);
 }
}

当然,您可以通过不同的方式实现 "localize" 逻辑(例如,正则表达式模式 + 替换)。但对于您的用例,我认为这是一个简单明了的开始。

只对那些词使用翻译管道(some statics words in my app like the application menu)

喜欢

{{ 'HOME.NAME' | translate }}

并从 api 数据中删除翻译过滤器