Angular4:用户的语言环境 [英] Angular4: Locale for a user
问题描述
我想拥有一个LoginForm,并且在该用户输入应用程序之后-使用德语或英语.据我了解,我可以在app.module.ts
中设置
I want to have a LoginForm and after this user enters the application - either with German or English usage. As far as I understand I can set in the app.module.ts
something like
import { LOCALE_ID } from '@angular/core';
providers: [{ provide: LOCALE_ID, useValue: 'de-DE' },...]
但是那是在启动时,而不是在已经显示LoginForm时:-/是否可以更改整个应用程序的语言环境? (不仅适用于特定组件!)-如果可以即时更改翻译,那就太好了.有什么提示如何实现?我只是找到了上面的处理方式.
But that is at the startup and not when the LoginForm was already displayed :-/ Is there a way to change the locale for the whole app? (Not only for a specific component!) - Would be great if the translations could be changed as well on the fly. Any hints how to achieve? I only found the above way to deal with.
推荐答案
我遵循了此线程的回答有以下解决方案:
I followed the answer from this thread and I have the following solution:
import { LOCALE_ID } from '@angular/core';
@NgModule({
// ...
providers: [...
{provide: LOCALE_ID,
deps: [SettingsService], // some service handling global settings
useFactory: getLanguage // returns locale string
}
]
// ...
})
export class AppModule { }
// the following function is required (for Angular 4.1.1!!!)
export function getLanguage(settingsService: SettingsService) {
return settingsService.getLanguage();
}
注意: :使用附加功能可防止错误Function calls are not supported. Consider replacing the function or lambda with a reference to an exported function
!!!!
我创建了类
import { Injectable } from '@angular/core';
@Injectable()
export class SettingsService {
currentLang: string;
constructor() {
this.currentLang = 'en';
}
setLanguage(lang: string) {
this.currentLang = lang;
}
getLanguage() {
return this.currentLang;
}
}
它会即时更改LOCALE_ID
:-)
这篇关于Angular4:用户的语言环境的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!