如何在Angular 4的扩展DatePipe自定义管道中设置区域设置?
在扩展Angular DatePipe时设置区域设置的方法
其实要给你这个自定义的DateTimeFormaterPipe设置区域设置,核心是要在继承DatePipe的时候,把区域参数传递给父类的构造函数。因为DatePipe本身的构造函数依赖区域设置,直接继承的话如果不传,就会用默认的英文区域,咱们来一步步改:
第一步:注入区域标识并传递给父类
首先要导入Angular的LOCALE_ID令牌和Inject装饰器,然后在管道的构造函数里注入这个区域标识,再传给父类的DatePipe构造函数。修改后的完整代码如下:
import { Pipe, PipeTransform, Inject } from '@angular/core'; import { DatePipe, LOCALE_ID } from '@angular/common'; @Pipe({ name: 'dateTimeFormater' }) export class DateTimeFormaterPipe extends DatePipe implements PipeTransform { // 注入LOCALE_ID,传递给父类DatePipe的构造函数 constructor(@Inject(LOCALE_ID) locale: string) { super(locale); } 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'].mediumDate; return super.transform(value, format); } }
第二步:配置全局区域(可选)
如果你的应用需要使用特定区域(比如中文zh-CN),可以在根模块(如AppModule)中注册区域数据并提供LOCALE_ID:
import { NgModule, LOCALE_ID } from '@angular/core'; import { registerLocaleData } from '@angular/common'; // 导入中文区域数据 import zh from '@angular/common/locales/zh'; // 注册区域数据,让Angular识别该区域的格式化规则 registerLocaleData(zh); @NgModule({ providers: [ { provide: LOCALE_ID, useValue: 'zh-CN' } ] }) export class AppModule { }
为什么要这么做?
DatePipe的父类构造函数必须接收locale参数来确定日期时间的格式化规则,咱们扩展它时如果不传递这个参数,Angular会默认使用en-US区域,格式化出来的就是英文风格的日期时间。上面的方法是最基础且通用的静态区域设置方案,如果之后需要动态切换区域,还可以结合区域服务类来实现。
内容的提问来源于stack exchange,提问作者Ivan Rodriguez
相关产品推荐
相关产品推荐

