Mat*_*ynn 5 c# asp.net-core blazor blazor-client-side
我们的 Blazor 应用程序正在运行preview9。
我正在尝试实现一个.razor组件,该组件侦听来自我们编写的 NotificationService 的事件,以便在调用服务时刷新视图,但我似乎遗漏了一些东西;
我有我的服务接口(为简洁起见减少了);
public interface INotificationService
{
event Action OnChange;
Task<ServiceResponse<Notification>> AddNotificationAsync(Notification notification);
}
Run Code Online (Sandbox Code Playgroud)
在我的实现中,我调用了该OnChange事件(为简洁起见,再次减少);
public async Task<ServiceResponse<Notification>> AddNotificationAsync(Notification notification)
{
/*...*/
StateChanged();
}
Run Code Online (Sandbox Code Playgroud)
在哪里StateChanged();
public event Action OnChange;
private void StateChanged() => OnChange?.Invoke();
Run Code Online (Sandbox Code Playgroud)
在我的Blazor.Client我决心INotificationService在ConfigureServices如下;
services.AddScoped<INotificationService, NotificationService>();
Run Code Online (Sandbox Code Playgroud)
然后我将服务注入到我想要订阅OnChange()事件的组件中;
@inject INotificationService NotificationService
protected override async Task OnInitializedAsync()
{
NotificationService.OnChange += StateHasChanged;
}
Run Code Online (Sandbox Code Playgroud)
然后在我的另一个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()
});
Run Code Online (Sandbox Code Playgroud)
但是,调用 tNotificationService.AddNotificationAsync不会触发组件的OnChange和 然后StateHasChanged是组件,因为组件没有刷新?任何想法我在这里做错了什么?
按照 Microsoft docs Invoke component methods external to update state,您应该更改:
@inject INotificationService NotificationService
protected override async Task OnInitializedAsync()
{
NotificationService.OnChange += StateHasChanged;
}
Run Code Online (Sandbox Code Playgroud)
经过:
@inject INotificationService NotificationService
protected override async Task OnInitializedAsync()
{
NotificationService.OnChange += OnNotify;
}
public async Task OnNotify()
{
await InvokeAsync(() =>
{
StateHasChanged();
});
}
Run Code Online (Sandbox Code Playgroud)
在您的代码中,您是StateHasChanged在 Blazor 的 SynchronizationContext 之外调用组件的方法。
InvokeAsync 用于切换到正确的上下文并将渲染排队。
| 归档时间: |
|
| 查看次数: |
2267 次 |
| 最近记录: |