Reputation:
I'm in the course of learning Angular2/Ionic2 so please excuse my ignorance. I got to learning Pipes and everything seemed easy until I stumbled on this problem. Let me demonstrate the problem using a perfect example with temperatures.
Say that I have pipe which return Celisus or Fahrenheit temperature value, depending on the setting saved on localStorage (Celsius is default input value).
So I created a Pipe which do this:
export class TemperatureConverterPipe implements PipeTransform {
// Selected temperature unit
private unit: string;
constructor(private settings: Settings){
// Get immediately the temperature unit from localStorage
// And subscribe to changes
this.settings.radio().subscribe(data => {
this.unit = data.temp_unit
});
}
// Return temperature
transform(value: number): number {
switch(this.unit){
case "c":
return value;
break;
case "f":
return celsiusToFahrenheit(value);
break;
default:
return value;
}
}
// Convert celsius temp to fahrenheit
celsiusToFahrenheit(value: number){
return value * 9/5 + 32;
}
}
Problems I'm stuck at:
Thank you very much!
Upvotes: 6
Views: 11774
Reputation: 29614
Pipe:
@Pipe(name: 'tempConverter')
export class TemperatureConverterPipe implements PipeTransform {
// Selected temperature unit
//private unit: string;
constructor(){
}
// Return temperature
transform(value: number,unit:string): number {
switch(unit){
case "c":
return value;
break;
case "f":
return celsiusToFahrenheit(value);
break;
default:
return value;
}
}
// Convert celsius temp to fahrenheit
celsiusToFahrenheit(value: number){
return value * 9/5 + 32;
}
}
HTML call:
[temperatureProperty]="value | tempConverter:unit"
Subscribe to the service in the ngOninit of calling component and pass unit.
Upvotes: 6
Reputation: 657356
You can make the pipe impure
@Pipe(name: 'tempConvert', pure: false)
export class TemperatureConverterPipe ...
this way the pipe is called every time change detection is run. With impure pipes you should ensure that the pipe doesn't do any expensive work because it will be called very often.
Upvotes: 0