我想在渲染 Blazor 應用程式之前加載一些資料,因為依賴于加載的資料,我想渲染我的應用程式(布局、導航欄 ...)
現在我想使用 OnInitialised 方法而不是 OnInitialisedAsync 并且沒有 async 和 await 關鍵字。
但是現在我在轉換從 API 回傳的資料時遇到了問題。

protected override void OnInitialized()
{
try
{ Console.WriteLine("Test1Mainasync");
LoadCategories();
}
catch (Exception e)
{
jsRuntime.ToastrError(e.Message);
}
}
private void LoadCategories()
{
IEnumerable<CategorieDTO> CategoriesInit1 = new List<CategorieDTO>();
CategoriesInit1 = categorieService.GetAllCategories();
SD.Categories = CategoriesInit1.ToList();
//foreach(var categorie in CategoriesInit){
// SD.Categories.Append(categorie);
//}
Console.WriteLine("Test1Main");
}
有人知道為什么會發生這種轉換問題嗎?
uj5u.com熱心網友回復:
我想你有這個方法:
public async Task<IEnumerable<CategorieDTO>> GetAllCategories()
你應該這樣稱呼它:
private async Task LoadCategories()
{
IEnumerable<CategorieDTO> CategoriesInit1 = new List<CategorieDTO>();
CategoriesInit1 = await categorieService.GetAllCategories();
和:
protected override async Task OnInitializedAsync()
{
try
{ Console.WriteLine("Test1Mainasync");
await LoadCategories();
}
uj5u.com熱心網友回復:
有人知道為什么會發生這種轉換問題嗎?
在您的代碼CatagiesInit1中是 a Task,它不是 a List<CategorieDTO>。您只能List<CategorieDTO>在任務完成時獲得您無法控制的任務,因為您沒有await完成任務。很可能,您的同步代碼將在此之前運行完成。
如果您CategoryService回傳 aTask那么處理它的代碼必須是異步代碼。你不能從異步世界逃回同步世界而沒有后果。如果您想生活在同步世界中,那么所有資料管道代碼也需要阻塞同步代碼。
如果我正確理解了您的評論,那么在滿足特定條件之前,您不希望渲染任何內容。如果是這樣,添加一些標準Loading...組件代碼到頁面,如果它是頁面特定的,或者App.razor如果它在初始加載,或者說它MainLayout是否是應用程式范圍的。
這是一個簡單的例子:
<Router AppAssembly="@typeof(App).Assembly">
<Found Context="routeData">
@if (Loaded)
{
<RouteView RouteData="@routeData" DefaultLayout="@typeof(MainLayout)" />
<FocusOnNavigate RouteData="@routeData" Selector="h1" />
}
else
{
<div class="m-2 p-5 bg-secondary text-white">
<h3>Loading.....</h3>
</div>
}
</Found>
<NotFound>
<PageTitle>Not found</PageTitle>
<LayoutView Layout="@typeof(MainLayout)">
<p role="alert">Sorry, there's nothing at this address.</p>
</LayoutView>
</NotFound>
</Router>
@code {
private bool Loaded;
protected override async Task OnInitializedAsync()
{
Loaded = false;
// simulate getting the data first
await Task.Delay(5000);
Loaded = true;
}
}
uj5u.com熱心網友回復:
您對 API 端點的呼叫回傳一個等待任務,但不是 IEnumerable,因此您不能將等待任務分配給 IEnumerable,因此這段代碼將無法作業
private void LoadCategories()
{
IEnumerable<CategorieDTO> CategoriesInit1 = new List<CategorieDTO>();
CategoriesInit1 = categorieService.GetAllCategories();
}
你應該有像這樣的 LoadCategories 函式
private async Task LoadCategories()
{
IEnumerable<CategorieDTO> CategoriesInit1 = new List<CategorieDTO>();
CategoriesInit1 = await categorieService.GetAllCategories();
}
API 呼叫應該是可等待的,否則它會卡住你的 UI
您也可以使用此解決方案
private void LoadCategories()
{
var t = Task.Run(() => categorieService.GetAllCategories()()).GetAwaiter();
t.OnCompleted(() =>
{
CategoriesInit1 = t.GetResult();
// you may need to call statehaschanged as well
StateHasChanged();
});
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/426632.html
上一篇:.NETCore/EF:如何避免Linq查詢的性能問題?
下一篇:EFCoreToArray模擬
