首页 > 解决方案 > 在初始化组件之前使用异步方法初始化 Blazor 范围服务

问题描述

我有一个范围服务:

services.AddScoped<UserSettingsService>();

我想在子组件初始化之前(之前)在服务上调用异步方法(从数据库加载数据ComponentBase.OnInitialized();

打电话的最佳地点在哪里UserSettingsService.LoadAsync();

我曾尝试在 OnInitializedAsync() 的 App 组件中执行此操作,但似乎为时已晚,因为我的子组件已在 UserSettingsService 之前初始化:

app.razor.cs:

public partial class App {
  [Inject] UserSettingsService UserSettingsService {get; set;}
  [Inject] AuthenticationStateService AuthenticationStateService {get; set;}
 
  public override async Task OnInitializedAsync() {
     string userName = (await AuthenticationStateService.GetAuthenticationState()).User.Identity.Name;
     await UserSettingsService.LoadAsync(userName );
     await base.OnInitializedAsync();
  }
}

标签: c#blazorblazor-server-side.net-5

解决方案


据我所知,SetparametersAsync应该做的伎俩。

图片非常清楚 blazor 组件生命周期: https ://knowledgebasehavit.files.wordpress.com/2019/11/blazor-component-lifecycle-diagram.png


推荐阅读