由于您的问题涉及到数据更改在显示原始数据之后,这可能会有所帮助:您可以在模型中添加一个标志以指示正在加载数据:
List<TestUser>? Users { get; set; }
protected override async Task OnAfterRenderAsync(bool firstRender)
{
if (this.Users == null)
{
this.Users = await this.GetUsersAsync();
// Notify that properties changed
this.StateHasChanged();
}
var onlineTasks = new List<Task>();
foreach (var user in this.Users)
{
onlineTasks.Add(Task.Run(async () =>
{
user.IsOnline = await this.GetIsOnlineAsync(user.Id);
}));
}
await Task.WhenAll(onlineTasks);
// Notify that properties changed
this.StateHasChanged();
}
// Implement your own API call
static readonly Random random = new Random();
private async Task<List<TestUser>> GetUsersAsync()
{
await Task.Delay(100);
return new()
{
new() { Id = 0, Name = "Foo", },
new() { Id = 1, Name = "Bar", },
new() { Id = 2, Name = "XYZ", },
};
}
// Implement your own API call using HttpClient
private async Task<bool> GetIsOnlineAsync(int id)
{
// Simulate a random delay
await Task.Delay((int)(random.NextDouble() * 3000));
// Here I just use this as example
return id % 2 == 0;
}
class TestUser
{
public int Id { get; set; }
public string Name { get; set; }
public bool? IsOnline { get; set; } // Null = no data yet
}
显示数据取决于数据状态:
<table>
<thead>
<tr>
<th>Name</th>
<th>Is Online?</th>
</tr>
</thead>
<tbody>
@if (this.Users != null)
{
foreach (var user in this.Users)
{
<tr>
<td>@(user.Name)</td>
<td>
@if (user.IsOnline == null)
{
<span class="text-muted">Loading...</span>
}
else if (user.IsOnline.Value)
{
<span class="text-success">Online!</span>
}
else
{
<span class="text-danger">Offline</span>
}
</td>
</tr>
}
}
</tbody>
</table>
您可以像在服务器端一样使用HttpClient 发出 HTTP 请求,但显然它会被转换为来自浏览器的 HTTP 请求,因此请记住存在限制。更多文档在这里:Call a web API from ASP.NET Core Blazor
首先,确保您注册了 HttpClient 服务。在默认模板中应该已经有一个,但如果没有:
builder.Services.AddScoped(sp =>
new HttpClient
{
BaseAddress = new Uri(builder.HostEnvironment.BaseAddress)
});
在您的 Blazor .razor 页面中:
// Inject the HttpClient service
@inject HttpClient Http;
// ...
// Request
List<TestUser>? users;
protected override async Task OnInitializedAsync()
{
var resObj = await this.Http.GetFromJsonAsync<TestResponse>("https://reqres.in/api/users?page=2");
this.users = resObj?.Data;
}
class TestResponse
{
public List<TestUser> Data { get; set; }
}
class TestUser
{
public int Id { get; set; }
public string First_Name { get; set; }
public string Last_Name { get; set; }
}
如何显示结果数据由您决定。见Razor syntax reference for ASP.NET Core。例如:
<table>
<thead>
<tr>
<th>Name</th>
<th>ID > 10?</th>
</tr>
</thead>
<tbody>
@if (this.users != null)
{
foreach (var user in this.users)
{
<tr>
<td>@(user.First_Name) @(user.Last_Name)</td>
<td>@(user.Id > 10 ? "Yes" : "No")</td>
</tr>
}
}
</tbody>
</table>