使用Blazor ClientSide应用程序实现事件订阅 [英] Implementing Event Subscription with Blazor ClientSide Application
问题描述
我们的Blazor应用程序在 preview9
上运行.
我正在尝试实现一个 .razor
组件,该组件侦听我们编写的NotificationService中的事件,以在每次调用该服务时刷新视图,但是我似乎缺少了一些东西; >
我有我的服务界面(为简洁起见,已简化);
公共接口INotificationService{事件动作OnChange;任务< ServiceResponse<通知>AddNotificationAsync(Notification notification);}
,在我的实现中,我调用 OnChange
事件(为简便起见再次降低);
公共异步任务< ServiceResponse<通知>>AddNotificationAsync(通知通知){/*...*/StateChanged();}
StateChanged()
在哪里;
公共事件Action OnChange;private void StateChanged()=>OnChange?.Invoke();
在我的 Blazor.Client
中,我按如下方法在 ConfigureServices
中解决了 INotificationService
;
services.AddScoped< INotificationService,NotificationService>();
然后我将服务注入到我要预订 OnChange()
事件的组件中;
@inject INotificationService NotificationService受保护的重写异步任务OnInitializedAsync(){NotificationService.OnChange + = StateHasChanged;}
然后在我的其他 razor
页面中,我再次注入相同的服务并调用 AddNotificationAsync
方法;
@inject INotificationService NotificationService等待NotificationService.AddNotificationAsync(新通知{级别= NotificationLevel.Success,Text = $已成功添加ID = {agreementType.Id}的协议类型.".ToString()});
但是,调用t NotificationService.AddNotificationAsync
不会触发组件的 OnChange
和 StateHasChanged
,因为该组件未刷新?有什么想法请问我在这里做错了吗?
以下Microsoft文档 However, calling t Following Microsoft docs Invoke component methods externally to update state, you should to change: By: In your code, you are invoking the component's InvokeAsync is used to switch to the correct context and queue a render.
这篇关于使用Blazor ClientSide应用程序实现事件订阅的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!NotificationService.AddNotificationAsync
is not triggering the OnChange
and then the StateHasChanged
of the component, as the component is not refreshing? Any ideas what I am doing wrong here please? @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();
});
}
StateHasChanged
method outside of Blazor's SynchronizationContext.