我想为基本的 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;
}
}
你可以扩展
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:
bootstrap(AppComponent, [CurrencyPipe]);
管道:
@Pipe({
name: 'mypipe'
})
export class MyPipe {
constructor(private cp: CurrencyPipe) {
}
transform(value: any, args: any[]) {
return this.cp.transform(value, args);
}
}
上面从一个管道扩展另一个管道的解决方案是可行的,但它提供了冗余的复杂性。如果遵循编程最佳实践,我们应该尽可能选择组合而不是继承。
这里的解决方案只是使用依赖注入将一个管道注入另一个管道(如@pixelbits 所建议的那样)。
但是这里还有一件更重要的事情是我们需要在我们正在使用的模块中向提供者数组添加可注入管道。
@NgModule(
providers: [PipeToBeInected]
) class MyModule {}
您可以在自定义管道中使用 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 上测试。