我有一个Blazor组件,正在测试API调用以获取天气数据。不知何故,必须单击两次提交按钮,才能显示更新后的对象属性。
页面初始化时,我可以很好地从浏览器中获取位置,并且天气数据可以正常显示在表格中。
FetchData.razor
@page "/fetchdata"
@using BlazingDemo.Client.Models
@using AspNetMonsters.Blazor.Geolocation
@inject HttpClient Http
@inject LocationService LocationService
<h1>Weather forecast</h1>
<p>This component demonstrates fetching data from the server.</p>
<div>
<EditForm Model="@weatherForm" OnValidSubmit="@GetWeatherDataAsync">
<DataAnnotationsValidator />
<ValidationSummary />
<InputText Id="cityName" bind-Value="@weatherForm.CityName" />
<button type="submit">Submit</button>
</EditForm>
</div>
<br />
@if (weatherData == null)
{
<Loader/>
}
else
{
<table class="table">
<thead>
<tr>
<th>City</th>
<th>Conditions</th>
<th>Temp. (C)</th>
</tr>
</thead>
<tbody>
<tr>
<td>@weatherData.Name</td>
<td>@weatherData.Weather[0].Main</td>
<td>@weatherData.Main.Temp</td>
</tr>
</tbody>
</table>
}
@functions {
WeatherFormModel weatherForm = new WeatherFormModel();
WeatherData weatherData;
Location location;
protected override async Task OnInitAsync()
{
location = await LocationService.GetLocationAsync();
if (location != null)
{
weatherData = await GetWeatherDataAsync(location.Latitude,location.Longitude);
}
}
protected async Task<WeatherData> GetWeatherDataAsync(decimal latitude, decimal longitude)
{
return await Http.GetJsonAsync<WeatherData>($"https://api.openweathermap.org/data/2.5/weather?lat={location.Latitude}&lon={location.Longitude}&units=metric&appid=***removed***");
}
protected async void GetWeatherDataAsync()
{
weatherData = await Http.GetJsonAsync<WeatherData>($"https://api.openweathermap.org/data/2.5/weather?q={weatherForm.CityName}&units=metric&appid=***removed***");
}
}
WeatherFormModel.cs
namespace BlazingDemo.Client.Models
{
public class WeatherFormModel
{
[Required, Display(Name = "City Name")]
public string CityName { get; set; }
public bool IsCelcius { get; set; }
}
}
我正在调用
GetWeatherDataAsync()
方法,并且通过检查 Chrome 返回的 JSON 数据,可以看到每次调用都会返回数据。但是在第一次单击时它不会更新表格。我已经尝试在调用该方法之前将 weatherData
设置为 null
,但那也不起作用。有什么建议吗?