Saj*_*ran 0 pipe typescript angular
我有一个管道转换货币如下,
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);
}
}
};
}
Run Code Online (Sandbox Code Playgroud)
在component.html中使用时效果很好.在一种情况下我需要在里面使用它,component.ts所以我正在使用它如下,
this.convertedPrice = CurrConvertPipe.prototype.transform(this.Price, this.selectedCurrency, this.movieticket.price.currency);
Run Code Online (Sandbox Code Playgroud)
这引发了一个错误说,
ERROR TypeError: Cannot read property 'getCurrencyRate' of undefined
我尝试创建一个管道实例,但它不允许我这样做.我如何在TS内消费?
您不能将transform方法用作static ...因为您在Pipe构造函数中具有依赖关系,Angular将从您解析并且您需要使用它.您需要通过依赖注入在组件中导入CurrConvertPipe的实例,就像在管道中为依赖项CurrencyUpdate和LocalStorageService一样.像这样的东西:
@Component
class SomeComponent {
constructor(private currConvertPipe: CurrConvertPipe ) { }
method() {
this.convertedPrice = this.currConvertPipe.transform(this.Price, this.selectedCurrency, this.movieticket.price.currency);
}
}
Run Code Online (Sandbox Code Playgroud)
希望这可以帮助.
| 归档时间: |
|
| 查看次数: |
439 次 |
| 最近记录: |