【问题标题】:Problem with extended DecimalPipe after upgrading to Angular 11升级到 Angular 11 后扩展的 DecimalPipe 出现问题
【发布时间】:2021-10-22 21:37:41
【问题描述】:

从 Angular 10 升级到 11 并遇到了我们在 DecimalPipe 上的扩展的问题。

管道代码:

 export class CustomNumberFormatPipe extends DecimalPipe implements PipeTransform {

 transform(value: string): string | null {
    if (!value) {
        return null;
    }
    value = value.toString().replace(/,/g, '');
    return super.transform(value);
}

和错误:

 Property 'transform' in type 'CustomNumberFormatPipe' is not assignable to the same property in base type 'DecimalPipe'.
 Type '(value: string) => string' is not assignable to type '{ (value: string | number, 
 digitsInfo?: string, locale?: string): string; (value: null, digitsInfo?: string, locale?: 
 string): null; (value: string | number, digitsInfo?: string, locale?: string): 
 string; }'.
 Type 'string' is not assignable to type 'null'.

以及 DecimalType 定义:

 export declare class DecimalPipe implements PipeTransform {
   private _locale;
   constructor(_locale: string);
   transform(value: number | string, digitsInfo?: string, locale?: string): string | null;
   transform(value: null | undefined, digitsInfo?: string, locale?: string): null;
   transform(value: number | string | null | undefined, digitsInfo?: string, locale?: string): string | null;
   static ɵfac: ɵngcc0.ɵɵFactoryDef<DecimalPipe, never>;
   static ɵpipe: ɵngcc0.ɵɵPipeDefWithMeta<DecimalPipe, "number">;

}

到目前为止,我发现的唯一解决方案是共同修改实际的 DecimalPipe,但我对此并没有信心。提前致谢。

【问题讨论】:

  • 尝试把这个transform(value: string): string改成这个transform(value: string): string | null。
  • 鉴于DecimalPipe 现在接受value 即null,您的子类也必须如此。您在实际实现中已经有了相应的逻辑,只需将其添加到类型定义中即可。
  • @R.Richards,尝试过但得到同样的错误

标签: angular angular11


【解决方案1】:

只需转到 DecimalPipe 声明并将其 transform 签名复制到您的管道:

transform(value: number | string, digitsInfo?: string, locale?: string): string | null;
transform(value: null | undefined, digitsInfo?: string, locale?: string): null;
transform(value: number | string | null | undefined, digitsInfo?: string, locale?: string): string | null {
    if (!value) {
        return null;
    }
    value = value.toString().replace(/,/g, '');
    return super.transform(value);
}

【讨论】:

  • @D Pro,我在问题中添加了定义,我不确定要添加哪个
  • 所有这些。我已经更新了我的答案,请检查
  • 谢谢大佬,成功了!
猜你喜欢
  • 2021-03-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-03-21
  • 2019-06-14
  • 2021-02-20
  • 2020-03-07
  • 2020-05-24
相关资源
最近更新 更多