Blazor 组件通信 StateContainer 调用不起作用

Blazor Component Communication StateContainer Invoke not working

我有一个具有以下内容的 AppState 服务:

public event Action OnDataChanged;
public MyObject CurrentObject { get; private set; }

public void UpdateMyObject(MyObject obj)
        {
            CurrentObject = obj;
            OnDataChanged?.Invoke();
        }

在一个组件中,我调用UpdateMyObjectAppState 服务确实命中了正确的数据,并调用了 OnDataChanged?.Invoke()

在应该订阅 OnDataChanged 以决定数据更新的另一个组件中,我有以下内容:

protected override void OnInitialized()
    {
        AppStateService.OnDataChanged+= UpdateData;
    }

 private void UpdateData()
    {
        var data = AppStateService.CurrentObject;
    }

我试图在整个 'listening' 组件中设置断点,但没有成功。关于我做错了什么以及为什么 UpdateData 方法没有从状态服务调用 OnChanged?.Invoke 有什么想法吗?有关如何调试的建议?

这是我的有效代码 - 我在 Blazor Server 模板解决方案中构建了它。为了简单起见,我将您的对象设为字符串。

public class AppState
{
    public Guid Id { get; } = Guid.NewGuid();

    public event Action? OnDataChanged;

    // This is more normal for events
    public event EventHandler? DataChanged;

    public string? CurrentObject { get; private set; }

    public void UpdateMyObject(string obj)
    {
        CurrentObject = obj;
        OnDataChanged?.Invoke();
        DataChanged?.Invoke(this, new EventArgs());
    }
}

服务注册

builder.Services.AddSingleton<WeatherForecastService>();
// Set as a singleton as the name suggests it's application specific and not user specific
builder.Services.AddSingleton<AppState>();

显示状态的组件

// AppStateComponent.razor
@inject AppState AppStateService
@implements IDisposable
<h3>AppStateComponent</h3>

<div class="m-2 p-2">
    Service ID: @this.AppStateService.Id.ToString()
</div>

<div>
    Data: @this.data
</div>
@code {

    private string data = string.Empty;

    protected override void OnInitialized()
    {
        this.AppStateService.OnDataChanged += UpdateData;
    }

    private void UpdateData()
    {
        data = this.AppStateService.CurrentObject!;
        this.InvokeAsync(StateHasChanged);
    }

    public void Dispose()
    {
        this.AppStateService.OnDataChanged -= UpdateData;
    }
}

还有一个测试页

@page "/"
@inject AppState AppStateService
<div class="m-2 p-2">
    Service ID: @this.AppStateService.Id.ToString()
</div>

<AppStateComponent />

<div class="m-2">
    <button class="btn btn-dark" @onclick=UpdateData>Update</button>
</div>

@code {

    private void UpdateData()
    {
        this.AppStateService.UpdateMyObject($"Updated at {DateTime.Now.ToLongTimeString()}");
    }
}