Angular2 Pipe to convert currency

2019-07-15 07:39发布

问题:

I have created a method to convert currency using a api, which looks as follows,

 exchange(Input: string, Output: string, value: number): number {
        let inputRate = this.currencyStorage.getCurrencyRate(cnput);
        let outputputRate = this.currencyStorage.getCurrencyRate(Output);
        return value/ inputRate * outputputRate;
    }

How can i create a pipe out of this which can be used throughout the application to convert currency ?

回答1:

@Pipe({name: 'currConvert'})
export class CurrConvertPipe implements PipeTransform {
  constructor(private currencyStorage:MyCurrencyStorage) {}

  transform(value: number, Input: string, Output: string): number {
    let inputRate = this.currencyStorage.getCurrencyRate(cnput);
    let outputputRate = this.currencyStorage.getCurrencyRate(Output);
    return value/ inputRate * outputputRate;
  }
}

register it with a modules declarations and use it like

{{123 | currConvert:456 /*input*/:789 /*output*/}}