我正在Angular中开发一个非常简单的气象应用程序,我想问一下您是否认为有更好的方法可以根据天气条件的“类型”选择特定的图像。
enum WeatherCodition {
Thunderstorm = 0,
Drizzle,
Rain,
Snow,
Clear,
Clouds
}
export class Weather {
getIcon(condition: WeatherCodition): string {
var iconPath = "";
switch(condition){
case WeatherCodition.Thunderstorm:
iconPath = "thunderstorm.png";
break;
case WeatherCodition.Clouds:
iconPath = "clouds.png";
break;
case WeatherCodition.Drizzle:
iconPath = "drizzle.png";
break;
case WeatherCodition.Rain:
iconPath = "rain.png";
break;
case WeatherCodition.Snow:
iconPath = "snow.png";
break;
default:
iconPath = "clear.png"
}
return iconPath;
}
}
最佳答案
您的方法非常好。您还可以创建哈希表以进行恒定时间查找,因为无论如何您都要在switch语句中编码网址。
interface WeatherIcons {
Thunderstorm: string;
Clouds: string;
}
const icons: WeatherIcons = {
Thunderstorm: "Thunderstorm.jpg",
Clouds: "Clouds.jpg"
}
function getIcon(condition: WeatherCondition) {
return icons[condition] || "default.jpg";
}