如何通过 aot 编译在 Angular 中提供备用 i18n 语言 link?

How to provide an alternate i18n language link in Angular with aot compiling?

我目前正在开发我的 Angular 应用程序的国际化。我使用 AOT 编译 xlf 文件来创建预编译的应用程序,如 here 所述。在构建中,我提供了特定于语言的基本 href(使用 --base-href 参数)。例如,这意味着,我最终使用以下 url 路径得到了两个特定于语言的应用程序:

现在我想在我的应用程序中为相应的替代语言提供 link,方法是在活动 url 中将 en 替换为 de。我使用了 Router 注入,所以我可以访问它的 url 属性,但是这个 属性 没有给我完整的 url包括 base-href.

如何从 Angular 应用程序中找到基础 url?

或者,有没有办法找出应用程序的构建语言?我能以某种方式从 xliff 文件访问目标语言 属性 吗?

首先,让 Angular 注入 Router 和 Location 对象(不确定为什么需要 Router):

constructor(private router: Router, private location: Location) {}

然后,确定基本路径(base href):

let fullpath = this.location.prepareExternalUrl(this.location.path());
let basepath = fullpath.substr(0, fullpath.lastIndexOf(this.location.path().substr(1)));

最后,这是创建备用语言 URL 列表的方法(在 urls 中):

const languages = ["en", "de", "fr", "it"];  // List of available languages 
let urls = [];
for (let lang of languages) {
  let url = basepath.replace(/\/(..)\/$/, "/" + lang + "/") + this.location.path().substr(1);
  if (url !== fullpath) {
    urls.push(url);
  }
}

请注意,basepath.replace 假定斜线之间有两个字符的语言代码。这不适用于 "en-us" 之类的东西,它需要稍微增强的正则表达式。我仍然没有找到一种方法来识别当前 运行 应用程序的语言。

当您为各种语言编译应用程序时,您在 ng 构建过程中设置了语言环境:

./node_modules/.bin/ngc --i18nFile=./locale/messages.es.xlf --locale=es --i18nFormat=xlf

您可以通过将其注入您的组件来访问此语言环境:

import { Inject, LOCALE_ID } from '@angular/core';
...
constructor(@Inject(LOCALE_ID) locale: string, ...

然后您可以使用语言环境字符串来确定当前语言。在上面的示例中,语言环境设置为 "es"

希望对您有所帮助