簡體   English   中英

Angular:在 node_module 組件中覆蓋 DatePipe

[英]Angular: Overriding DatePipe in node_module components

問題:我的 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' 它觸發了我的擴展 pipe 而不是 Angular 的。

至於 node_modules 組件,它仍然觸發默認的 Angular DatePipe 而不是我的擴展。 我認為這與構建 angular 架構和編譯器首先編譯 node_modules 的方式有關。 不完全確定。 只是想看看是否有人遇到過類似的問題,以及是否有任何神奇的解決方案。 謝謝!

您只需要設置正確的提供者:

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

這將為所有想要 DatePipe 的人提供 MyDatePipe。

顯然這已被棄用,現在您只需將其添加到您的 App 模塊聲明中。 查看答案覆蓋 Angular 默認日期 pipe

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM