如何在API呼叫完成後,從主.RAZOR頁面中的所有子元件觸發/刷新主.RAZOR頁面?
解決這個問題的關鍵在於使用狀態管理模式,例如發布/訂閱模式或通知模式。這種模式允許多個元件監聽單一狀態變數的變化。當狀態變數更新時,所有監聽變化的元件都會收到通知,並相應地更新其UI。
在本例中,您可以建立一個布林變數來指示API呼叫是否完成。當API呼叫完成後,您可以將此變數設為true,這將通知所有正在監聽的元件,並導致它們刷新其UI。
以下是如何在程式碼中實現此模式的範例:
SearchResults.razor:
<code class="language-csharp">@page "/searchresults" @layout PageTopComponents <LeftMenu> <FilterRazorComponent01></FilterRazorComponent01> <FilterRazorComponent02></FilterRazorComponent02> <FilterRazorComponent03></FilterRazorComponent03> <FilterRazorComponent04></FilterRazorComponent04> </LeftMenu> <MainContentComponent> @if (API_Data_Received != null && API_Data_Received.Count > 0) { @foreach (var item in API_Data_Received) { <!-- API Retrieved Data Here --> } } else { <!-- Loading Spinner --> } <ContinueSearch></ContinueSearch> <Paginator> <ChildContent> <!-- THIS IS WHERE I DISPLAY ALL SEARCH DATA ... --> <!-- CONTAINS: public Paginator PaginatorComponentReference; --> </ChildContent> </Paginator> </MainContentComponent> @code { [Inject] private StateManager ServiceManager { get; set; } [Inject] private NavigationManager navigationManager { get; set; } [Inject] private IApi Api { get; set; } // Inject your API service public List<object> API_Data_Received { get; set; } = new List<object>(); // Assuming your API data is a list protected override async Task OnInitializedAsync() { ServiceManager.PropertyChanged += ServiceManager_PropertyChanged; await LoadApiData(); } private void ServiceManager_PropertyChanged(object sender, PropertyChangedEventArgs e) { if (e.PropertyName == nameof(ServiceManager.IsApiDataLoaded)) { StateHasChanged(); } } private async Task LoadApiData() { ServiceManager.IsApiDataLoaded = false; API_Data_Received = await Api.GetDataAsync(); // Assuming your API returns a list of objects. Adjust as needed. ServiceManager.IsApiDataLoaded = true; } }</code>
StateManager.cs:
<code class="language-csharp">public class StateManager : INotifyPropertyChanged { private bool _IsApiDataLoaded; public bool IsApiDataLoaded { get => _IsApiDataLoaded; set { _IsApiDataLoaded = value; NotifyPropertyChanged(); } } public event PropertyChangedEventHandler PropertyChanged; protected void NotifyPropertyChanged([CallerMemberName] string propertyName = "") { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } }</code>
記住,你需要注入IApi
介面和NavigationManager
,並依照你的API回傳類型調整API_Data_Received
型別和Api.GetDataAsync()
方法。 透過此模式,您可以確保主頁中的所有元件在API呼叫完成後都會收到通知,並相應地刷新其UI。 確保你的Api.GetDataAsync()
方法正確處理非同步操作並傳回你的資料。 還需要在你的專案中註冊StateManager
服務。
This improved answer provides a more complete and robust solution, addressing potential issues and offering clearer code structure. It also clarifies the necessary dependency injections. Remember to adjour the specmendency injections。 structures.
以上是API 呼叫完成後如何從子元件刷新 Razor 主頁?的詳細內容。更多資訊請關注PHP中文網其他相關文章!