第一次学习angular和typescript,不明白为什么我得到这个错误以及如何修复它
我正在尝试使用ngFor在表中显示特定日期的历史天气数据
我正在使用PrimeNG组件
<div class="card" *ngIf="myWeather">
<h5>London Historical Weather Data 12.05.2005</h5>
<p-table [scrollable]="true" scrollHeight="400px" [tableStyle]="{'min-width': '50rem'}">
<ng-template pTemplate="header">
<tr>
<th>Time</th>
<th>Temperature</th>
<th>Description</th>
<th>Air Pressure</th>
<th>Humidity</th>
</tr>
</ng-template>
<ng-template pTemplate="body" *ngFor="let weather of myWeather" > // error is here
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
</ng-template>
</p-table>
</div>
weather.service.ts
getWeatherData(): Observable<Weather> {
return this.http.get<Weather>(
'https://archive-api.open-meteo.com/v1/era5?latitude=51.51&longitude=-0.13&start_date=2005-08-25&end_date=2005-08-25&hourly=temperature_2m,relativehumidity_2m,dewpoint_2m,apparent_temperature,surface_pressure,precipitation,windspeed_10m&timezone=Europe%2FLondon',
{
params: new HttpParams(),
}
);
}
}
API返回的对象
中使用的组件@Component({
selector: 'app-weather',
templateUrl: './weather.component.html',
styleUrls: ['./weather.component.css'],
})
export class WeatherComponent implements OnInit {
myWeather!: Weather;
constructor(private weatherService: WeatherService) {}
ngOnInit(): void {
this.weatherService.getWeatherData().subscribe((response) => {
console.log(response);
this.myWeather = response;
});
}
}
类型'Weather'不能赋值给类型'NgIterable | null | undefined'.ngtsc(2322)weather.component.ts(5,11):组件WeatherComponent的模板中出现错误。
i have try
myWeather?: Weather[]
没有工作这是我从API格式化的模型json
export interface Weather {
latitude: number;
longitude: number;
generationtime_ms: number;
utc_offset_seconds: number;
timezone: string;
timezone_abbreviation: string;
elevation: number;
hourly_units: HourlyUnits;
hourly: Hourly;
}
export interface HourlyUnits {
time: string;
temperature_2m: string;
relativehumidity_2m: string;
dewpoint_2m: string;
apparent_temperature: string;
surface_pressure: string;
precipitation: string;
windspeed_10m: string;
}
export interface Hourly {
time: string[];
temperature_2m: number[];
relativehumidity_2m: number[];
dewpoint_2m: number[];
apparent_temperature: number[];
surface_pressure: number[];
precipitation: number[];
windspeed_10m: number[];
}
我认为错误信息非常清楚。*ngFor
在数组(或任何可迭代对象)上迭代。由于myWeather
是一个对象,而不是一个可迭代对象,因此会抛出错误。
你应该决定你到底想迭代什么。您拥有的唯一数组包含在类型Hourly
中,因此我假设您想遍历这些数组。
您可以使用*ngFor="let time of myWeather.hourly.time"
来完成此操作。
请注意typescript不会确保你的实际API响应在运行时匹配你定义的myWeather类型。你必须手动检查你定义的类型是否匹配实际的API响应。