【问题标题】:extend a pipe like currency or number on a custom pipe on angular2在angular2上的自定义管道上扩展货币或数字等管道
【发布时间】:2016-12-22 14:29:01
【问题描述】:

我想在我的自定义管道上调用 numberPipe 我找到了这个答案

Angular2 use basic pipe in custom pipe

但我这个解决方案对我不起作用。我有一个错误 “找不到管道‘bigInteger’”

import { Pipe, PipeTransform } from "@angular/core"
import { CurrencyPipe  } from "@angular/common"

@Pipe({
 name: "bigInteger"
 })
 export class BigInteger extends CurrencyPipe implements PipeTransform {
   transform(value: any): string {
    return value
 }
}

【问题讨论】:

    标签: angular typescript pipe


    【解决方案1】:

    可能已经过时,但这对我有用(Angular 5):

    import { Pipe, PipeTransform } from '@angular/core';
    import { DecimalPipe } from '@angular/common'
    
    @Pipe({
      name: 'bigInteger'
    })
    export class BigInteger extends DecimalPipe implements PipeTransform {
      transform(value: any, args?: any): any {
    
        let result;
        result = super.transform(value, args);
    
        //any transformations you need
    
        return result;
      }
    
    }
    

    然后你就像普通的 number 管道一样使用它,但可以根据需要自定义:

    <span>{{someValue | bigInteger : '1.2-2'}}</span>
    

    【讨论】:

      【解决方案2】:

      更新

      这应该至少在 Angular4 中修复一段时间

      原创

      DI 和扩展其他类的类存在一个已知问题

      https://github.com/angular/angular/issues/8694

      在解决此问题后,您可以使用组合而不是继承:

      @Pipe({
        name: "bigInteger"
      })
      export class BigInteger implements PipeTransform {
      
        constructor(private currencyPipe:CurrencyPipe) {}
      
        transform(value: any): string {
           return this.currencyPipe.transform(value);
        }
      }
      

      【讨论】:

      • 除此之外,我在视图模板中使用自定义管道时也遇到了错误,抱怨没有 CurrencyPipe 的提供程序。所以为了解决这个错误,在我的 app.module.ts 中,我将它添加到了 Providers 列表中:providers: [..., CurrencyPipe] 现在我基于它的自定义管道可以工作了!现在,我确信这可能不是最佳做法或其他什么,但我需要找到一些合理的方法来覆盖默认管道,或者也许有更好的方法?
      • 另外,CurrencyPipe 可以在 Angular 的 Common 模块 import { CurrencyPipe } from '@angular/common'; 中找到
      猜你喜欢
      • 2017-07-05
      • 1970-01-01
      • 2016-12-13
      • 1970-01-01
      • 2016-12-24
      • 2018-07-18
      • 1970-01-01
      • 2016-06-18
      • 2021-11-10
      相关资源
      最近更新 更多