Angular2 在 Component.js 中使用管道

Angular2 Using Pipes in Component.js

我正在学习 Angular2,我想格式化一个添加千位逗号分隔符的数字。据我所知,这可以使用管道来完成,问题是我想在 js 文件中以编程方式格式化数字,而不是在 html 中(像 var | number 一样)。

首先我意识到没有我可以使用的 NumberPipe 独立管道(如果我错了请纠正我)最相似的是@angular2/common 中的 CurrencyPipe。所以我有这样的东西:

import { Component } from '@angular/core';
import { CurrencyPipe } from '@angular/common';

@Component({
  templateUrl: 'test.component.html',
  styleUrls: ['./test.component.scss']
})
export class TestComponent {
    public myNumber = 1000;

    constructor(private currencyPipe: CurrencyPipe) {    
        var formatted = this.currencyPipe().transform(this.myNumber, 'MXN', true); // Is this correct?
    }

}

但它抛出以下错误: 未处理的承诺拒绝:没有 CurrencyPipe 的提供者! ;区域:angular ;...

我做错了什么?

提前致谢。

此致

第一件事:你需要声明你的管道——将它添加到 NgModule declarations 部分:

declarations: [CurrencyPipe]

第二件事:管道不是可注入的,所以你不能使用 Angular 依赖注入系统来获取它的实例。您需要手动创建此管道的新实例,例如:

var formatted = (new CurrencyPipe()).transform(this.myNumber, 'MXN', true);

这实际上可以在 @Injectable 显示实用程序服务中工作,甚至比以前涉及模块的答案更简单。我导入了我的数据模型(如下)和管道,然后简单地添加了函数。所以,如果你不能在标记中直接使用管道,请使用这个技巧!

export interface MoneyDTO extends SerializableDTO, JsonModelObjectDTO {
  value?: string;
  currency?: string;
}

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

formatMoney(money: MoneyDTO): string {
  const cp: CurrencyPipe = new CurrencyPipe('en-US');

  return money && money.value ? cp.transform(money.value, money.currency || 'USD', 'symbol') : null;
}