与单例服务Blazor Serverside的两种方式数据绑定 [英] Two way databinding to singleton service Blazor Serverside
问题描述
我一直在使用Webassembly在客户端上使用Blazor.但是我认为我现在应该尝试服务器端版本,并且我有一个简单的想法想尝试一下.
I have been playing with Blazor on the client using Webassembly quite a bit. But I thought I would try the serverside version now and I had a simple idea I wanted to try out.
所以我的理解是Blazor服务器端使用SignalR来推送"更改,以便客户端重新呈现其页面的一部分.
So my understading was that Blazor serverside uses SignalR to "push" out changes so that the client re-renders a part of its page.
我想尝试的是将数据绑定到单例服务上的属性,如下所示:
what I wanted to try was to databind to a property on a singleton service like this:
@page "/counter"
@inject DataService dataService
<h1>Counter</h1>
<p>Current count: @currentCount ok</p>
<p> @dataService.MyProperty </p>
<p>
@dataService.Id
</p>
<button class="btn btn-primary" @onclick="IncrementCount">Click me</button>
@code {
int currentCount = 0;
void IncrementCount()
{
currentCount++;
dataService.MyProperty += "--o--|";
}
}
Startup.cs:
Startup.cs:
public void ConfigureServices(IServiceCollection services)
{
services.AddRazorPages();
services.AddServerSideBlazor();
services.AddSingleton<WeatherForecastService>();
services.AddSingleton<DataService>();
}
服务:
namespace bl1.Services
{
public class DataService
{
public DataService()
{
this.Id = System.Guid.NewGuid().ToString();
}
public string Id {get;set;}
public string MyProperty { get; set; }
}
}
所以我的问题是这个.为什么,如果我在两个选项卡中打开此页面,当我更改另一个选项卡中一个选项卡上属性的值时,我没有立即看到使用SignalR更新的属性 MyProperty 的值?是否有一个不应该起作用的原因,或者我只是做错了吗?
So my question is this. Why, if I open up this page in two tabs, do I not immediately see the value being updated for the property MyProperty with SignalR when I am changing the value on the property in one tab in the other tab? Is there a reason that is not supposed to work or am I just simply doing it wrong?
我认为在服务器端使用Blazor的好处是,您可以轻松使用SignalR可用这一事实,并在服务器上的值更改时获得实时更新.
I thought the upside of using Blazor on the serverside was that you could easily use the fact that SignalR is available and get live updates when values change on the server.
我确实从另一个选项卡中的单例服务中获得了最新的价值,但只有在单击那里的按钮之后.
I do get the latest value from the singleton service in the other tab but only after I click the button there.
推荐答案
Invoking StateHasChanged()
on the client should fix the problem.
对于您描述的问题,您最好使用普通的SignalR,而不是Blazor服务器端.
For the problem you describe you better use plain SignalR, not Blazor serverside.
这篇关于与单例服务Blazor Serverside的两种方式数据绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!