使用 Blazor 客户端应用程序实现事件订阅

Implementing Event Subscription with Blazor ClientSide Application

我们的 Blazor 应用 运行 preview9

我正在尝试实现一个 .razor 组件来侦听来自我们编写的 NotificationService 的事件,以便在调用服务时刷新视图,但我似乎遗漏了一些东西;

我有我的服务接口(为简洁起见减少了);

public interface INotificationService
{
    event Action OnChange;
    Task<ServiceResponse<Notification>> AddNotificationAsync(Notification notification);
}

在我的实现中,我调用了 OnChange 事件(为简洁起见再次减少);

public async Task<ServiceResponse<Notification>> AddNotificationAsync(Notification notification)
{
    /*...*/

    StateChanged();
}

其中StateChanged()是;

public event Action OnChange;

private void StateChanged() => OnChange?.Invoke();

在我的 Blazor.Client 中,我在 ConfigureServices 中解决了 INotificationService 如下;

services.AddScoped<INotificationService, NotificationService>();

然后我将服务注入我想要订阅 OnChange() 事件的组件;

 @inject INotificationService NotificationService

 protected override async Task OnInitializedAsync()
 {
     NotificationService.OnChange += StateHasChanged;
 }

然后在我的另一个 razor 页面中,我再次注入相同的服务并调用 AddNotificationAsync 方法;

@inject INotificationService NotificationService

  await NotificationService.AddNotificationAsync(
                            new Notification { 
                                Level = NotificationLevel.Success, 
                                Text = $"Agreement Type with Id = {agreementType.Id} has been successfully added.".ToString()
                            });

但是,调用t NotificationService.AddNotificationAsync 是不是触发了组件的OnChange,然后又是StateHasChanged,因为组件没有刷新?请问我做错了什么吗?

根据 Microsoft 文档 Invoke component methods externally to update state,您应该更改:

 @inject INotificationService NotificationService

 protected override async Task OnInitializedAsync()
 {
     NotificationService.OnChange += StateHasChanged;
 }

作者:

 @inject INotificationService NotificationService

 protected override async Task OnInitializedAsync()
 {
     NotificationService.OnChange += OnNotify;
 }


 public async Task OnNotify()
 {
    await InvokeAsync(() =>
    {
        StateHasChanged();
    });
 }

在您的代码中,您将在 Blazor 的 SynchronizationContext 之外调用组件的 StateHasChanged 方法。

InvokeAsync is used to switch to the correct context and queue a render.