从管道更改语言时如何更改日期格式

How to change the date format when changing languages from a pipe

我有一个管道可以让我根据 eeee d MMMM yyyy.

格式更改日期格式

我使用date-fns更改日期格式并使用本地库更改翻译。

我也用ngx-translate来翻译申请。

当我打开应用程序时,管道会更改带有正确翻译的日期格式,但当我更改语言时,管道不会更新。

这里是使用的管道:

   import { Pipe, PipeTransform } from '@angular/core';
   import { LangChangeEvent, TranslateService } from '@ngx- 
   translate/core';
   import { format } from 'date-fns';
   import { enGB } from 'date-fns/locale'
   import { fr } from 'date-fns/locale'

   @Pipe({name: 'convertDate'})
   export class ConvertDate implements PipeTransform {
   constructor(public _translateSrvc: TranslateService) {}
   transform(value: string) {

   let formatter: string = this._translateSrvc.currentLang === 'fr' ? 'eeee d MMMM yyyy' : 'eeee d MMMM yyyy';
   let localeLang = this._translateSrvc.currentLang === 'fr' ? fr : enGB;
   let resultDate = format(new Date(value), 'eeee d MMMM yyyy', {locale: localeLang});

   this._translateSrvc.onLangChange.subscribe((event: LangChangeEvent) => {
   localeLang = this._translateSrvc.currentLang === 'fr' ? fr : enGB;
   resultDate = format(new Date(value), 'eeee d MMMM yyyy', {locale: localeLang});
  });

    return resultDate;
  }
}

检测到语言的变化,确认语言已经变化,格式的变化也做得很好

this._translateSrvc.onLangChange.subscribe((event: LangChangeEvent) => {
     localeLang = this._translateSrvc.currentLang === 'fr' ? fr : enGB;
     resultDate = format(new Date(value), 'eeee d MMMM yyyy', {locale: 
     localeLang});
 });

但是管道没有return新格式

这里是使用的组件:

  import {Component} from '@angular/core';
  import {TranslateService} from '@ngx-translate/core';

  @Component({
  selector: 'app-root',
  template: `
  <div>
  <h2>{{ 'HOME.TITLE' | translate }}</h2>
  <label>
    {{ 'HOME.SELECT' | translate }}
    <select #langSelect (change)="translate.use(langSelect.value)">
      <option *ngFor="let lang of translate.getLangs()" [value]="lang" [selected]="lang === translate.currentLang">{{ lang }}</option>
    </select>
  </label>

  <div *ngFor="let player of players"> 
  <ul>
    <li>{{player.date | convertDate}}</li>
  </ul>
  </div>
</div>
 `,
})
export class AppComponent {
  constructor(public translate: TranslateService) {
translate.addLangs(['en', 'fr']);
translate.setDefaultLang('en');

const browserLang = translate.getBrowserLang();
translate.use(browserLang.match(/en|fr/) ? browserLang : 'en');
 }

  players  = [{name: 'Gene', team: 'team alpha', date: '2019-09-18T16:45:42' },
 {name: 'Steve', team: 'team gamma', date: '2019-09-18T15:45:42'},
 {name: 'George', team: 'team beta', date: '2019-09-18T12:45:42'},
 {name: 'Paula', team: 'team beta', date: '2019-09-18T15:45:42'},
 {name: 'Jhon', team: 'team gamma', date: '2019-09-18T15:45:42'}];
}

Stackbiltz demo

如何让管道在语言改变时立即改变格式?

您需要在装饰中添加以下内容:

pure: false

这样试试:

@Pipe({ name: 'convertDate',pure: false })

Working Demo

有关 pure 的更多信息,请阅读这篇文章 article