【问题标题】:Angular2 use basic pipe in custom pipeAngular2在自定义管道中使用基本管道
【发布时间】:2016-06-18 21:49:55
【问题描述】:

我想为基本的 angular2 管道添加一些额外的功能。

即。在货币管道上完成了一些额外的格式化。为此,我想在自定义管道的组件代码中使用现有管道。

有什么办法可以做到吗?

@Pipe({name: 'formatCurrency'})
export class FormatCurrency implements PipeTransform {
  transform(value:number, args:string[]) : any {
    var formatted = value/100;

    //I would like to use the basic currecy pipe here.
    ///100 | currency:'EUR':true:'.2'

    return 'Do some extra things here ' + formatted;
  }
}

【问题讨论】:

    标签: angular angular-pipe


    【解决方案1】:

    你可以扩展CurrencyPipe,像这样:

    export class FormatCurrency extends CurrencyPipe implements PipeTransform {
      transform(value: any, args: any[]): string {
        let formatedByCurrencyPipe = super.transform(value, args);
        let formatedByMe;
        // do your thing...
        return formatedByMe;
      }
    }
    

    如果您查看source,这与角管的工作原理类似...


    (由问题作者添加)

    别忘了导入 CurrencyPipe 类

    import {CurrencyPipe} from 'angular2/common'; 
    

    【讨论】:

    • 谢谢!我在您的答案中添加了导入行,必须搜索才能找到 CurrencyPipe 的导入位置。
    • 过时的答案,这里有更好的方法:*.com/questions/35144821/…
    • 既然可以将 CurrencyPipe 放入构造函数并使用它,为什么还要扩展它?
    【解决方案2】:

    或者,您可以注入 CurrencyPipe:

    bootstrap(AppComponent, [CurrencyPipe]);
    

    管道:

    @Pipe({
        name: 'mypipe'
    })
    export class MyPipe {
        constructor(private cp: CurrencyPipe) {
        }
        transform(value: any, args: any[]) {
            return this.cp.transform(value, args);
        }
    }
    

    【讨论】:

    • 我也喜欢这种方式。 CurrencyPipe 提供者还有其他方法吗?将其添加到引导程序似乎有点混乱。我尝试了以下但没有成功:@Pipe({ name: 'formatCurrency', providers: [CurrencyPipe], pipe: [CurrencyPipe] })
    • 好问题。我认为您还可以将 [CurrencyPipe] 指定为组件的依赖项:providers: [CurrencyPipe]。我同意,太糟糕了,它在管道级别不起作用。
    • 我刚刚导入了包含实际管道的模块(它是自定义管道而不是默认的 Angular 管道,但我认为没关系)并且我已经能够将它注入另一个管道(这两个不在同一个模块中)没有问题。
    【解决方案3】:

    您可以在自定义管道中使用 Angular 管道。

    首先,在您的管道文件中,您必须导入所需的管道,例如。

    import { SlicePipe } from '@angular/common';
    

    然后在你的自定义管道中使用它:

      transform(list: any, end: number, active: boolean = true): any {
    return active ? new SlicePipe().transform(list, 0, end) : list;
    

    }

    在 A6 上测试。

    【讨论】:

    • 虽然这适用于简单的情况,但要小心实例化应该是 DI-d 的对象。
    最近更新 更多