Angular中如何使用新模型格式化天气API返回数据
适配单对象参数的WeatherDataItem模型方案
问题梳理
原代码通过多参数构造函数生成WeatherDataItem实例,改用仅接收单个对象参数的新模型后,因传入参数格式(多参数/数组)与构造函数要求不匹配,触发“期望1个参数却传入9个”的报错,需调整模型定义和组件传参逻辑。
修正后的WeatherDataItem模型
完善构造函数的参数类型(避免使用泛泛的Object),并优化赋值逻辑:
// 定义与类结构一致的输入数据类型 interface WeatherDataInput { temperature: number; time: string; humidity: number; wind: number; pressure: number; direction: string; precipitation: Rain; cloudcover: number; soilTemperature: number; } export class WeatherDataItem { temperature: number; time: string; humidity: number; wind: number; pressure: number; direction: string; precipitation: Rain; cloudcover: number; soilTemperature: number; constructor(inputData: WeatherDataInput) { // 逐个赋值或用Object.assign简化 this.temperature = inputData.temperature; this.time = inputData.time; this.humidity = inputData.humidity; this.wind = inputData.wind; this.pressure = inputData.pressure; this.direction = inputData.direction; this.precipitation = inputData.precipitation; this.cloudcover = inputData.cloudcover; this.soilTemperature = inputData.soilTemperature; // 简洁写法:Object.assign(this, inputData); } }
组件订阅代码修改
在forEach循环中,将原多参数调用改为传入单个结构匹配的对象:
weatherData: WeatherDataItem[] = []; … this.weatherService.getWeather() .subscribe({ next: (historicalWeatherData) => { const temperatures = historicalWeatherData.hourly.temperature_2m; const times = historicalWeatherData.hourly.time.map((time) => this.datePipe.transform(time, 'shortTime') ); const humidities = historicalWeatherData.hourly.relativehumidity_2m; const windSpeeds = historicalWeatherData.hourly.windspeed_10m; const airPressures = historicalWeatherData.hourly.surface_pressure; const windDirections = historicalWeatherData.hourly.winddirection_10m.map((item) => this.checkWindDirection(item) ); const precipitations = historicalWeatherData.hourly.precipitation.map( (item) => { if (item > 0) { return new Rain(item, true); } return new Rain(item, false); } ); const cloudcover = historicalWeatherData.hourly.cloudcover; const soilTemperatures = historicalWeatherData.hourly.soil_temperature_0_to_7cm; temperatures.forEach((value, i) => { // 构造符合要求的单个对象参数 const weatherItemData = { temperature: value, time: times[i], humidity: humidities[i], wind: windSpeeds[i], pressure: airPressures[i], direction: windDirections[i], precipitation: precipitations[i], cloudcover: cloudcover[i], soilTemperature: soilTemperatures[i] }; this.weatherData.push(new WeatherDataItem(weatherItemData)); }); ...
关键说明
- 类型必须明确:使用
Object会丢失TS类型检查,必须定义与类结构匹配的具体类型(如WeatherDataInput接口)。 - 传参格式要匹配:新模型仅接收单个对象参数,不能传多参数或数组,需将原索引对应的字段值包装成结构一致的对象。
- 类型一致性:注意新模型将原
string类型的数值字段改为number,需确保API返回的temperatures、humidities等字段本身是数字类型(若为字符串需额外转换)。
内容的提问来源于stack exchange,提问作者krk5570
相关产品推荐
相关产品推荐

