在Angular 8中即时更改moment.js语言环境

时间:2020-02-16 00:45:19

标签: angular momentjs locale

我需要

标题。我的应用程序中有一个语言选择器,到目前为止,我一直在使用它来动态(无需刷新页面)更改应用程序中的语言。当我尝试使用moment.js'moment.locale(string)进行此操作时,它不会像其他应用程序一样更新视图。

setLocale(locale?: string) {
    if (!locale) locale = localStorage.getItem("locale") || "en-US";
    localStorage.setItem("locale", locale);
    this.adapter.setLocale(locale); //for date picker (nothing to do with moment.js)
    moment.locale(locale); // for moment.js ------------------- only works after refresh
    this.translate.use(locale); //rest of the app
}

这是从下拉菜单中选择一种语言时调用的方法,但是由moment.js渲染的日期不会更新,直到页面刷新。

有没有办法做到这一点?哈克?解决方法?

谢谢

1 个答案:

答案 0 :(得分:0)

@Pipe({
  name: 'dynamicMoment'
})
export class MomentPipe implements PipeTransform {
  /**
   * MomentPipe constructor
   * @param {TranslateService} translate
   */
  constructor(private translate: TranslateService) {
  }

  /**
   * Make moment dynamic
   * @param {string} value
   * @param {string} format
   * @returns {any}
   */
  transform(value: string, format?: string): any {
    // make the moment format configurable
    format = format ? format : 'MMMM Do YYYY';
    // get the initial value
    const initVal = moment(value).locale(moment.locale()).format(format);
    // insert the value into a new behaviour subject. If the language changes, the behaviour subject will be 
    // updated
    const momentObs = new BehaviorSubject<string>(initVal);
    this.translate.onLangChange.subscribe(() => {
      // format the new date according to the new locale
      const val = moment(value).locale(moment.locale()).format(format);
      momentObs.next(val);
    });
    return momentObs; // needs to be piped into the async pipe
  }

}