简体   繁体   English

Angular:在 node_module 组件中覆盖 DatePipe

[英]Angular: Overriding DatePipe in node_module components

Problem: I have an external library in my angular app with components.问题:我的 angular 应用程序中有一个带有组件的外部库。 Some of this components use Angular DatePipe internally to transform dates in the 'shortDate' format.其中一些组件在内部使用 Angular DatePipe 以“shortDate”格式转换日期。 I don't really have the option to use any other component or implement a custom one as it's a requirement for the client to use that specific library.我真的没有选择使用任何其他组件或实现自定义组件,因为客户端需要使用该特定库。 But of course they don't want 'shortDate' format aswell.但他们当然也不想要“shortDate”格式。

I tried extendeding the built-in Angular DatePipe.我尝试扩展内置的 Angular DatePipe。 As follows:如下:

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);
  }

}

This works for any custom-component that i have currently implemented in my app.这适用于我当前在我的应用程序中实现的任何自定义组件。 Whenever i use 'my_var |每当我使用'my_var | date' it triggers my extended pipe instead of Angular's. date' 它触发了我的扩展 pipe 而不是 Angular 的。

As for node_modules components it still triggers the default Angular DatePipe instead of my extended one.至于 node_modules 组件,它仍然触发默认的 Angular DatePipe 而不是我的扩展。 I assume this has to do with the way the angular architecture is built and the compiler compiles node_modules first.我认为这与构建 angular 架构和编译器首先编译 node_modules 的方式有关。 Not entirely sure.不完全确定。 Just wanted to see if anyone came accross a similiar problem, and if there's any magical solution.只是想看看是否有人遇到过类似的问题,以及是否有任何神奇的解决方案。 Thank you!谢谢!

You just have to set the correct provider:您只需要设置正确的提供者:

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

This will provide MyDatePipe to everyone wanting DatePipe.这将为所有想要 DatePipe 的人提供 MyDatePipe。

Apparently this is deprecated, and now you should simply add it in your App module declarations.显然这已被弃用,现在您只需将其添加到您的 App 模块声明中。 See answer Override Angular default date pipe查看答案覆盖 Angular 默认日期 pipe

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM