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
Angular2 i18n language switch
提问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"
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');