There is a way to inject and call a service within a pipe? I have a service with currencies and I want to use it to get the name based on the id. Thanks!!
This is my code:
@Pipe({name: 'currencypipe', pure: false})
export class CurrencyPipe implements PipeTransform {
symbol: string = null;
constructor(private currencyService: CurrencyService) {
}
transform(value: number, currencyId: number): Promise<String> {
return this.currencyService.getCurrencie(currencyId).then(response => {
return (value + " " + response.symbol);
}
);
}
}
And I use it like this
{{3 | currencypipe: 2 | async}}
You may inject service in pipes like you do in any component,
@Pipe({
name: 'my-currency-pipe'
})
export class MyCurrencyPipe implements PipeTransform {
constructor(service: SomeService) {
}
transform(value: string): string {
return value;
}
}
However you may also use Parameter in pipes. Read more here.
Update
excerpts from Pipe documentation search for An impure caching pipe,
Let's write one more impure pipe, a pipe that makes an HTTP request to the server. Normally, that's a horrible idea. It's probably a horrible idea no matter what we do. We're forging ahead anyway to make a point. Remember that impure pipes are called every few microseconds. If we're not careful, this pipe will punish the server with requests.
Keeping above in mind, you can do below for your scenario to get result asynchronously,
import { Component, PipeTransform, Pipe } from '@angular/core';
export class CurrencyService {
getCurrencie(currencyId):Promise<string> {
return new Promise<any>((resolve, reject) => {
setTimeout(() => {
if(currencyId === 1 ){
resolve({symbol : '$'});
}else{
resolve({symbol: '£'});
}
}, 1000)
})
}
}
@Pipe({name: 'currencypipe', pure: false})
export class CurrencyPipe implements PipeTransform {
symbol: string = null;
prevalue: string = null;
result: string = '';
constructor(private currencyService: CurrencyService) {
}
transform(value: number, currencyId: number) {
if (value !== this.prevalue) {
this.prevalue = value;
this.result = '';
this.currencyService.getCurrencie(currencyId).then(response => {
this.result = value + " " + response.symbol;
}
);
}
return this.result;
}
}
@Component({
selector: 'my-app',
template: `<h1>Currency Pipe</h1>
<hr />
{{3 | currencypipe: 1 }}
`
})
export class AppComponent { }
@NgModule({
imports: [ BrowserModule ],
declarations: [ AppComponent, CurrencyPipe ],
providers: [ CurrencyService ],
bootstrap: [ AppComponent ]
})
export class AppModule { }
Here is Plunker!!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With