如何在Blazor服务器端更新多个用户? [英] How do I update multiple users on Blazor Server-Side?

查看:66
本文介绍了如何在Blazor服务器端更新多个用户?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我想要一个用户组中的用户具有同步视图的UI.想象一下一个小组聊天应用程序,该小组中的每个人都应该看到完全相同的消息.

Suppose I want a UI where users in a group have a synchronized view. Imagine a group-chat application, where everyone in the group should see the exact same messages.

当用户向该组发布消息时,整个组都需要接收该消息.

When a user posts a message to the group, the entire group needs to receive it.

使用JS,我可能会使用SignalR组,并让前端生成带有消息的SignalR事件.然后,服务器端集线器会将消息发送给该组.

With JS, I might use SignalR Groups, and have the front-end generate a SignalR event with a message is posted. The server-side hub would then send that message out to the group.

在服务器端Blazor上,由于所有用户的状态都已在服务器上,我将如何协调更新Blazor上的用户组的UI?

On Server-Side Blazor, since all the users' states are already on the server, how would I coordinate updating the UI of groups of users on Blazor?

推荐答案

我正在尝试实现类似的目标.一段时间后,我发现了一种方法.凯尔(Kyle)的回答帮助我弄清楚了.

I was trying to achieve something similar. After a while, I discovered a way of doing this. Kyle's answer helped me figure it out.

您必须创建一个类,让我们调用 Messenger ,该类具有Action属性,并且一旦调用该方法便会调用该Action

You must create a class, let's call Messenger, which has an Action property, and a method that invokes this Action once called

public Action OnMessage { get; set; }
public void AddMessage(string message)
{
  Text = message;
  OnMessage?.Invoke();
}

在剃须刀组件中,注入Messenger.另外,您应该将事件设置为OnMessage属性,然后调用StateHasChanged以便告诉视图它可以更新

In the razor component, inject the Messenger. Also, you should set an event to the OnMessage property, and then call StateHasChanged in order to tell the view that it can update

@inject Messenger messenger
// rest of component here, and then the code block 
protected override async Task OnInitializedAsync()
{
  messenger.OnMessage += () =>
  {
    // do something with the messenger.Text here
    InvokeAsync(this.StateHasChanged);
  };
}

别忘了,在您的Startup类中,将Messenger类添加为Singleton以便进行注入

Don't forget, on your Startup class, add the class Messenger as a Singleton in order to have it available for injection

services.AddSingleton<Messenger>();

我希望这是您要实现的目标,它也可以帮助其他人.干杯.

I hope that is what you were trying to achieve, and it can help others as well. Cheers.

这篇关于如何在Blazor服务器端更新多个用户?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆