我想要一个 LoginForm 并且在此用户输入应用程序后 - 使用德语或英语。据我了解,我可以在 app.module.ts
中设置类似
import { LOCALE_ID } from '@angular/core';
providers: [{ provide: LOCALE_ID, useValue: 'de-DE' },...]
但那是在启动时,而不是在 LoginForm 已经显示时:-/有没有办法更改整个应用程序的语言环境? (不仅针对特定组件!) - 如果翻译也可以即时更改,那就太好了。任何提示如何实现?我只找到了上面的处理方式。
最佳答案
我遵循了 this thread 的答案我有以下解决方案:
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();
}
注意:使用额外函数可防止错误不支持函数调用。考虑将函数或 lambda 替换为对导出函数的引用
!!!!
然后我创建了类
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
:-)
关于 Angular 4 : Locale for a user,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43918376/