Home >Backend Development >C++ >How to Refresh a Blazor Main Razor Page from Child Components After an API Call?
In Blazor, we often encounter situations where we need to dynamically update the main page layout or refresh content based on events or actions triggered in nested child components (such as API call completion).
Consider the following scenario:
To achieve the above solutions, we utilize the following technologies:
We use scoped services (such as AppState) to store and share the retrieved API data so that it can be accessed by both the root page and its subcomponents.
We define a reusable Loading.razor component that displays the spinner when the page loads and content when the data is ready.
We create a view service (e.g. WeatherForecastViewService) that manages the data and exposes a ListChanged event that is fired when the underlying data changes.
In the child component, we inject the view service and monitor its ListChanged event. After a change is detected, we use StateHasChanged to refresh the component and display the updated data.
In the main SearchResults.razor page we:
<code class="language-csharp">@code { [Inject] WeatherForecastViewService viewService { get; set; } // API 调用完成后赋值为 true public bool IsLoaded { get; set; } protected override async Task OnInitializedAsync() { await GetForecastsAsync(); this.viewService.ListChanged += this.OnListChanged; } private async Task GetForecastsAsync() { // 代码省略,为简洁起见 } private void OnListChanged(object sender, EventArgs e) => this.InvokeAsync(this.StateHasChanged); public void Dispose() { this.viewService.ListChanged -= this.OnListChanged; } }</code>
<code class="language-csharp">@if (this.IsLoaded) { @this.ChildContent } else { // 显示加载微调器 }</code>
By implementing these techniques, we establish a communication channel between child components and the main page, allowing us to trigger UI updates and maintain consistent data state across parent-child relationships.
The above is the detailed content of How to Refresh a Blazor Main Razor Page from Child Components After an API Call?. For more information, please follow other related articles on the PHP Chinese website!