Reputation: 222722
I have a pipe to convert currency as follows,
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);
}
}
};
}
which works very well when using in component.html. In one case i need to use this inside the component.ts
so i am consuming it as follows,
this.convertedPrice = CurrConvertPipe.prototype.transform(this.Price, this.selectedCurrency, this.movieticket.price.currency);
this throws an error saying,
ERROR TypeError: Cannot read property 'getCurrencyRate' of undefined
I tried creating an instance of the pipe, but it does not allow me to do so. how can i consume inside TS?
Upvotes: 0
Views: 694
Reputation: 2638
You can't use the transform method as static... because you have dependencies in your Pipe constructor that Angular resolves from you and you need to use. You need import the instance of CurrConvertPipe in your component via Dependency Injection, as you do in your pipe for the dependencies CurrencyUpdate and LocalStorageService. Something like that:
@Component
class SomeComponent {
constructor(private currConvertPipe: CurrConvertPipe ) { }
method() {
this.convertedPrice = this.currConvertPipe.transform(this.Price, this.selectedCurrency, this.movieticket.price.currency);
}
}
Hope this helps.
Upvotes: 5