我遵循了 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
来提供 TRANSLATIONS
和LOCALE_ID
基于您的配置。
您仍然需要在语言更改时重新启动您的应用程序,这反过来意味着重新加载,但是,嘿,用户在浏览器中缓存了这个包,所以重新加载应该非常快。
无论如何,到目前为止,如果您想获得真正的动态翻译,我建议您使用 ngx-translate .
除了 translate
管道和服务,他们还有这个不错的 speculative polyfill当 Angular i18n
正式支持代码翻译时,这可能会让您省去一些麻烦。
关于javascript - Angular 2 i18n 动态/即时翻译,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42024207/