Angular4:用户的区域设置

前端之家收集整理的这篇文章主要介绍了Angular4:用户的区域设置前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我希望有一个LoginForm,并在此用户输入应用程序后 – 使用德语或英语.据我所知,我可以在app.module.ts中设置类似的东西
  1. import { LOCALE_ID } from '@angular/core';
  2. providers: [{ provide: LOCALE_ID,useValue: 'de-DE' },...]

但那是在启动时,而不是在LoginForm已经显示的时候: – /有没有办法改变整个应用程序的语言环境? (不仅仅是针对特定组件!) – 如果翻译可以随时更改,那将会很棒.任何提示如何实现?我只找到了上面的处理方式.

我按照 this thread的答案,我有以下解决方案:
  1. import { LOCALE_ID } from '@angular/core';
  2.  
  3. @NgModule({
  4. // ...
  5. providers: [...
  6. {provide: LOCALE_ID,deps: [SettingsService],// some service handling global settings
  7. useFactory: getLanguage // returns locale string
  8. }
  9. ]
  10. // ...
  11. })
  12. export class AppModule { }
  13. // the following function is required (for Angular 4.1.1!!!)
  14. export function getLanguage(settingsService: SettingsService) {
  15. return settingsService.getLanguage();
  16. }

注意:使用额外函数可防止错误不支持函数调用.考虑使用对导出函数的引用来替换函数或lambda!

我创建了这个类

  1. import { Injectable } from '@angular/core';
  2.  
  3. @Injectable()
  4. export class SettingsService {
  5. currentLang: string;
  6.  
  7. constructor() {
  8. this.currentLang = 'en';
  9. }
  10.  
  11. setLanguage(lang: string) {
  12. this.currentLang = lang;
  13. }
  14. getLanguage() {
  15. return this.currentLang;
  16. }
  17. }

它会动态更改LOCALE_ID

猜你在找的Angularjs相关文章