0

问题:我的 Angular 应用程序中有一个带有组件的外部库。其中一些组件在内部使用 Angular DatePipe 以“shortDate”格式转换日期。我真的没有选择使用任何其他组件或实现自定义组件,因为客户端需要使用该特定库。但他们当然也不想要“shortDate”格式。

我尝试扩展内置的 Angular DatePipe。如下:

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

@Pipe({
  name: 'date'
})
export class DateExtendedPipe extends DatePipe implements PipeTransform {

  static readonly DEFAULT_FORMAT = 'dd/MM/yyyy';
  
  constructor(@Inject(LOCALE_ID) locale: string) {
    super(locale)
  }

  transform(value: Date | string | number, format?: string, timezone?: string, locale?: string): string | null;
  transform(value: null | undefined, format?: string, timezone?: string, locale?: string): null;
  transform(value: Date | string | number | null | undefined, format?: string, timezone?: string, locale?: string): string | null {
    console.log('date format');
    
    const ghibFormat = format && format !== 'shortDate' ? format : DateExtendedPipe.DEFAULT_FORMAT;
    return super.transform(value, ghibFormat, timezone, locale);
  }

}

这适用于我当前在我的应用程序中实现的任何自定义组件。每当我使用'my_var | date' 它会触发我的扩展管道而不是 Angular 的。

至于 node_modules 组件,它仍然会触发默认的 Angular DatePipe 而不是我的扩展。我认为这与构建角度架构的方式有关,并且编译器首先编译 node_modules。不完全确定。只是想看看是否有人遇到过类似的问题,以及是否有任何神奇的解决方案。谢谢!

4

1 回答 1

0

您只需要设置正确的提供者:

  providers: [{
    provide: DatePipe,
    useClass: MyDatePipe
  }]

这将为所有想要 DatePipe 的人提供 MyDatePipe。

显然这已被弃用,现在您只需将其添加到您的 App 模块声明中。请参阅答案覆盖 Angular 默认日期管道

于 2021-12-07T15:27:40.630 回答