Angular4: Locale for a user

北慕城南 提交于 2019-12-05 03:25:00
LeO

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();
}

Note: The usage of an extra function prevents the error Function calls are not supported. Consider replacing the function or lambda with a reference to an exported function !!!!

and I create the class

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;
  }
}

which changes the LOCALE_ID on the fly :-)

What you're doing in app.module.ts is the right way to do this and for the whole app:

@NgModule({
  // ...
  providers: [
    { provide: LOCALE_ID, useValue: 'de-DE'}
  ]
  // ...
})
export class AppModule { }

But unfortunately I don't think that it's possible to change it on the fly.

How about this?

  • use local storage to store the locale (eg. 'fr')
  • load the associated translation file in main.ts (eg. messages.fr.xlf)
  • set the LOCALE_ID in app.module.ts

To change the locale

  • set the new locale in local storage
  • refresh the app

main.ts

declare const require;

const locale = localStorage.getItem('locale');
const translation = require(`raw-loader!./locale/messages.${locale}.xlf`)

platformBrowserDynamic().bootstrapModule(AppModule, {
  providers: [
    {provide: TRANSLATIONS, useValue: translation},
    {provide: TRANSLATIONS_FORMAT, useValue: 'xlf'}
  ]
});

app.module.ts

@NgModule({
  providers: [
    {provide: LOCALE_ID, useValue: localStorage.getItem('locale')}
  ]
})
export class AppModule { }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!