如何从Blazor的不同API路线获得另一个列表



我遇到了一个难题,我想知道如何解决这个问题。我正在努力学习Blazor,我正在使用一个开放的API来接收关于《权力的游戏屋》及其所有宣誓成员的数据。所以我基本上想收到的是另一个列表中的一个列表,但有两条不同的路线。我期望的输出是点击一个房子的名字,另一个列表应该添加到我的成员表中

预期输出

House Targaryen - Daenerys Targaryen
- Aegon Targaryen

等等。。。

房屋路线https://anapioficeandfire.com/api/houses/378字符路由https://anapioficeandfire.com/api/characters/33

@page "/fetchdata"
@using System.Text.Json.Serialization
@using System.Text.Json
@inject HttpClient Http

<h1>Game of Thrones</h1>
<p>This component demonstrates fetching data from the server.</p>
@if (houses == null)
{
<p>
<em>Loading...</em>
</p>
}
else
{
<table class="table">
<thead>
<tr>
<th>Houses</th>
</tr>
</thead>
<tbody>
@foreach (var house in houses.Take(5))
{
<tr>
<td>@house.Name</td>
@foreach (var character in house.SwornMembers.Take(5))
{
<td>
<tr>@character</tr>
</td>
}
</tr>
}
</tbody>
</table>
}
@code {
List<House> houses;
List<Character> characters;
protected override async Task OnInitializedAsync()
{
houses = await Http.GetFromJsonAsync<List<House>>("https://anapioficeandfire.com/api/houses/");
Console.WriteLine(houses);
}
public class House
{
public string Name { get; set; }
public List<Character> SwornMembers { get; set; }
}
public class Character
{
public string Name { get; set; }
public string Gender { get; set; }
public string Culture { get; set; }
public string Born { get; set; }
}
}

快速浏览一下api,您就不能通过以下方式加载多个字符:?id=1,2,3,4.

就像timur说的,你将不得不打一堆GetFromJSONAsync电话。如果您查看json响应,SwornMembers属性不是一个对象,而是一个必须单独加载的URL。在House类中,将List<Character>更改为List<string>

然后创建一个接受url的CharacterFromApi组件。<CharacterFromApi URL="@character"/>

@foreach (var character in house.SwornMembers.Take(5))
{
<td>
<tr><CharacterFromApi URL="@character"/></tr>
</td>
}
//FYI the usings can be moved into the _Imports.razor file
@using System.Text.Json.Serialization
@using System.Text.Json
@inject HttpClient Http
<div>
@(Character?.Name)
</div>
@code {
[Parameter] 
public string URL { get; set; }   
Character Character { get; set; }
protected override async Task OnInitializedAsync()
{
Character = await Http.GetFromJsonAsync<Character>(URL);
}
public class Character
{
public string Name { get; set; }
public string Gender { get; set; }
public string Culture { get; set; }
public string Born { get; set; }
}
}

相关内容

  • 没有找到相关文章