我有一个管道来转换货币,如下所示,
import { Pipe, PipeTransform } from '@angular/core';
import { LocalStorageService } from 'storage.service';
import { CurrencyUpdate } from 'update';
import { Observable } from 'rxjs/Observable';
@Pipe({name: 'currConvert'})
export class CurrConvertPipe implements PipeTransform {
errorMessage: string;
constructor(private currencyStorage: LocalStorageService, private currencyConversion: CurrencyUpdate) {
}
transform(value: number, toCurrency: string, baseCurrency: string): any {
if (toCurrency && baseCurrency) {
const outputRate = this.currencyStorage.getCurrencyRate(baseCurrency, toCurrency);
if (!outputRate) {
return this.currencyConversion.getExchangeRate(toCurrency, baseCurrency).map((rate: any) => {
const currency = {
fromCurrency: baseCurrency,
toCurrency,
exchangeRate: rate
};
this.currencyStorage.saveCurrencies(currency);
return value * rate;
}, (error: any) => this.errorMessage = error);
} else {
return Observable.of(value * outputRate);
}
}
};
}
在component.html中使用时非常有效。在一种情况下,我需要在 component.ts
中使用它,所以我按照以下方式使用它,
this.convertedPrice = CurrConvertPipe.prototype.transform(this.Price, this.selectedCurrency, this.movieticket.price.currency);
这会引发错误,
ERROR TypeError: Cannot read property 'getCurrencyRate' of undefined
我尝试创建管道实例,但它不允许我这样做。我如何在TS内消费?
答案 0 :(得分:5)
您不能将transform方法用作静态...因为您在Pipe构造函数中具有Angular从您解析并且您需要使用的依赖项。您需要通过依赖注入在组件中导入CurrConvertPipe的实例,就像在管道中为依赖项CurrencyUpdate和LocalStorageService一样。这样的事情:
Door door = new WoodenDoor(100, 200);
希望这有帮助。