最初,我对 DatePipe 进行了简单的扩展,以从我们的标准(YYYYMMDD 格式)转换日期值,以便 Angular 中的 DatePipe 可以使用它。
export class SlsDatePipe extends DatePipe implements PipeTransform {
constructor(Locale:string) {
super(Locale);
}
/**
* Convert the data from the numeric YYYYMMDD to the Javascript date format
* @param DateValue SLS Formatted number in the YYYYMMDD style
* @param args Angular Date Pipe args to control the output format
* @returns Text output following the Javascript date() formats
*/
public transform(DateValue:number, args:string):string | null {
const DateString:string = DateValue.toString();
const Year:number = parseInt(DateString.substr(0, 4), 10);
const Month:number = parseInt(DateString.substr(4, 2), 10) - 1;
const Day:number = parseInt(DateString.substr(6, 2), 10);
const DateObject:Date = new Date(Year, Month, Day);
return super.transform(DateObject, args);
}
在类中有一些额外的检查以确保正确的格式等,但问题的基础已经存在。这在 Angular 10 中有效。我刚刚更新到 Angular 11,代码现在在转换时产生错误:
error TS2416: Property 'transform' in type 'SlsTimePipe' is not assignable to the same property in base type 'DatePipe'.
Type '(TimeValue: number, args: string) => string' is not assignable to type '{ (value: string | number | Date, format?: string, timezone?: string, locale?: string): string; (value: null,
format?: string, timezone?: string, locale?: string): null; (value: string | number | Date, for mat?: string, timezone?: string, locale?: string): string; }'.
Type 'string' is not assignable to type 'null'.