Изменить момент. js локаль на лету в Angular 8 - PullRequest
0 голосов
/ 16 февраля 2020

НАЗВАНИЕ - это то, что мне нужно. В моем приложении есть раскрывающийся список выбора языка, и до сих пор я использовал его для динамического (без обновления страницы) изменения языка в приложении. Когда я пытался сделать это, используя момент. 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
}

Этот метод вызывается, когда язык выбирается из раскрывающийся список, но даты, отображаемые в данный момент. js не обновляются, но до обновления страницы sh.

Есть ли способ сделать это? Hack? Обходной путь?

Спасибо

1 Ответ

0 голосов
/ 16 февраля 2020

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

}
...