Currently I am diving into Angular2/Ionic2 and trying to grasp the concept of Pipes. Everything was going smoothly until I faced a roadblock in the form of a specific problem related to temperatures.
Let me illustrate my issue with an example involving temperature conversions between Celsius and Fahrenheit.
Suppose I have a custom Pipe that returns either Celsius or Fahrenheit temperature values, based on the user's setting stored in localStorage (Celsius being the default input value).
To tackle this, I created the following Pipe:
export class TemperatureConverterPipe implements PipeTransform {
// Selected temperature unit
private unit: string;
constructor(private settings: Settings){
// Fetch the temperature unit from localStorage immediately
// And listen for changes
this.settings.radio().subscribe(data => {
this.unit = data.temp_unit
});
}
// Convert temperature based on chosen unit
transform(value: number): number {
switch(this.unit){
case "c":
return value;
break;
case "f":
return celsiusToFahrenheit(value);
break;
default:
return value;
}
}
// Function to convert celsius to fahrenheit
celsiusToFahrenheit(value: number){
return value * 9/5 + 32;
}
}
The two main issues I am grappling with are:
- How can this Pipe monitor changes in parameters (temperature unit) and update the output accordingly (e.g., switching from C to F)? Currently, it only detects input changes (temperature value).
- Is this the correct approach to address this scenario?
Your insights and assistance are greatly appreciated!