How do I update multiple users on Blazor Server-Side?

后端 未结 1 987
孤街浪徒
孤街浪徒 2021-02-10 09:51

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.

Wh

1条回答
  •  执笔经年
    2021-02-10 10:13

    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();
    

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

    0 讨论(0)
提交回复
热议问题