typescript Angular2 i18n 语言切换

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39894394/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 03:54:38  来源:igfitidea点击:

Angular2 i18n language switch

angulardynamictypescriptinternationalizationswitching

提问by Loic T

I'm looking for a way to

我正在寻找一种方法

  • set dynamically the current language to be displayed: I have followed the latest angular cookbook hereabout internationalization but it says "the user's language is hardcoded as a global document.locale variable in the index.html"
  • 动态设置要显示的当前语言:我在此处遵循了有关国际化的最新 angular 食谱但它说“用户的语言被硬编码为 index.html 中的全局 document.locale 变量

How can this be set dynamically in angular2 + typescript ?

如何在 angular2 + typescript 中动态设置?

Here is my attempt from the official Angular2 plunkr : https://plnkr.co/edit/lWV4VhzpWYnCXeDBpzsn?p=previewwhere I've commented out the

这是我从官方 Angular2 plunkr 的尝试:https://plnkr.co/edit/lWV4VhzpWYnCXeDBpzsn?p =preview 我已经注释掉了

document.locale='en';

and tried to retrieve the window.document inside a typescript service, and change the locale there, but despite it is called and the locale set properly (seen in the console), the interface is not displayed in the chosen language at startup.

并尝试在打字稿服务中检索 window.document 并更改那里的语言环境,但是尽管它被调用并且语言环境设置正确(在控制台中看到),但在启动时界面并未以所选语言显示。

Then of course the dropdown buttons don't work either because the same erroneous way is used and the display is not refreshed but that is the next step.

然后当然下拉按钮也不起作用,因为使用了相同的错误方式并且显示没有刷新,但这是下一步。

采纳答案by user3506588

I am saving user selected language key into local storage:

我正在将用户选择的语言密钥保存到本地存储中:

//<select name="selectLocate" (change)="onChange($event.target.value)">
 public onChange(localeId: string): void {
    localStorage.setItem('localeId', localeId);
    location.reload(true);
  }

Then force reloading, and in i18n.provider.ts

然后强制重新加载,然后在 i18n.provider.ts

let locale = localStorage.getItem('localeId');