我有一个从DataPipe Angular类扩展的自定义管道。

import { Pipe, PipeTransform } from '@angular/core';
import { DatePipe } from '@angular/common';

@Pipe({
  name: 'dateTimeFormater'
})
export class DateTimeFormaterPipe extends DatePipe implements PipeTransform {
  transform(value: any): string {
    const currentDay = new Date().getDay();
    const itemDate = new Date(value);
    const elementDay = itemDate.getDay();
    const format = currentDay === elementDay ? DatePipe['_ALIASES'].mediumTime : DatePipe['_ALIASES'].shortDate;
    return super.transform(value, format );
  }
}


我需要通过用户语言(而不是浏览器配置)设置区域设置(全局)值。当用户登录到应用程序时,此值从数据库获取。例如,我在app.module中有此值。

基类有一个带有locale参数的构造函数,但是我不知道如何用locale值进行调用。根据上下文或用户设置,该值可能会有所不同。

//common/pipes/ts/date_pipe.ts (angular code)

export declare class DatePipe implements PipeTransform {
  private _locale;
  constructor(_locale: string);
    transform(value: any, pattern?: string): string | null;
}

最佳答案

基于我的Angular 5版本中的基类。

export declare class DatePipe implements PipeTransform {
    private locale;
    constructor(locale: string);
    transform(value: any, format?: string, timezone?: string, locale?: string): string | null;
}


您可以使用管道的这种格式将语言环境作为构造函数传入管道。

import { Pipe, PipeTransform } from '@angular/core';
import { DatePipe } from '@angular/common';

@Pipe({
  name: 'dateTimeFormater'
})
export class DateTimeFormaterPipe extends DatePipe implements PipeTransform {

    constructor(locale: string){
        super(locale);
    }
  transform(value: any,format?:string): string {
    const currentDay = new Date().getDay();
    const itemDate = new Date(value);
    const elementDay = itemDate.getDay();
    const format = currentDay === elementDay ? DatePipe['_ALIASES'].mediumTime : DatePipe['_ALIASES'].shortDate;
    return super.transform(value, format );
  }
}


然后像这样使用它。

新的DateTimeFormaterPipe('en-US')。transform(date_value,'yyyy-MM-dd HH:mm:ss')

“ en-US”是您的语言环境。

关于javascript - 如何在angular 4的扩展数据管道中设置语言环境?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/49430257/

10-10 23:18
查看更多