javascript - Angular 2 i18n 动态/即时翻译

标签 javascript angular typescript internationalization

我遵循了 angular.io 国际化指南 ( https://angular.io/docs/ts/latest/cookbook/i18n.html#!#angular-i18n )。 一切正常,如果我在 index.html 文件中更改语言环境:

document.locale = 'en';

但我希望动态更改它,就像我们过去在 AngularJS 中所做的那样。我找到了几种解决方案,例如:

//mycomponent.component.ts
changeLang(){
localStorage.setItem('localeId', "es");
location.reload(true);

} //I hardcoded the locale, but you get the idea

有没有办法随时随地翻译文档?因为这个解决方案不实用,并且重新加载时间很长。谢谢您的帮助!

最佳答案

简而言之,由于翻译工作是由 Angular 编译器完成的,因此在不重新加载应用程序的情况下无法更改语言环境。


截至今天,您有 two options使用官方 Angular i18n 时:

使用AOT compiler

在这种情况下,将为每个语言环境创建一个单独的包,您将不得不交换整个应用程序,即重新加载它。

When you internationalize with the AOT compiler, you must pre-build a separate application package for each language and serve the appropriate package based on either server-side language detection or url parameters.

使用JIT compiler

这种方法的性能较低,但您不一定需要每种语言的 bundle 。
在这种情况下,您使用 webpack 加载翻译文件,并在引导期间将其提供给 Angular 编译器。

The JIT compiler compiles the app in the browser as the app loads. Translation with the JIT compiler is a dynamic process of:

  • Importing the appropriate language translation file as a string constant.
  • Creating corresponding translation providers for the JIT compiler.
  • Bootstrapping the app with those providers.

虽然在官方文档中他们只有 useValue 提供程序的示例,但我很确定您可以使用 useFactory 来提供 TRANSLATIONSLOCALE_ID 基于您的配置。
您仍然需要在语言更改时重新启动您的应用程序,这反过来意味着重新加载,但是,嘿,用户在浏览器中缓存了这个包,所以重新加载应该非常快。


无论如何,到目前为止,如果您想获得真正的动态翻译,我建议您使用 ngx-translate .
除了 translate 管道和服务,他们还有这个不错的 speculative polyfillAngular i18n 正式支持代码翻译时,这可能会让您省去一些麻烦。

关于javascript - Angular 2 i18n 动态/即时翻译,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42024207/

相关文章:

javascript - 这段代码中的循环引用在哪里?

angularjs - Angular 1 到 Angular 5(导入嵌套组件)

css - 避免在 mat-selection-list 组件中突出显示边框

asp.net - 如何在 ASP.Net MVC 中从 JavaScript 转换为 TypeScript?

c# - .net core 2.2 带有 typescript 和 signalr

javascript - CreateJS EaselJS - 不同形状的旋转处理不一致

javascript - 使用单选按钮将值从 html 表单传递到 javascript 函数

angular - 如何在 Angular 2/Angular - Cli 中解析 tsx 文件

javascript - 覆盖 js.erb 文件

angular - "as"中的 "response.json() as Hero[]"有什么作用?