问题
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.
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.
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?
回答1:
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.
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();
}
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);
};
}
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.
来源:https://stackoverflow.com/questions/59696970/how-do-i-update-multiple-users-on-blazor-server-side