解决这个问题的一个可行方案是在服务中实现状态模式和通知模式,以保持对象的状态并通知订阅对象的更改。因此,您可以创建一个服务来缓存员工集合,允许对象(本例中的主要组件)将员工添加到该集合中,并通知订阅者(newrecord)该事实,从而启用对该集合的访问,或者更好地以事件args对象的形式将其从服务传递到订阅者对象。下面是如何实现状态模式和通知模式的基本示例(注意:此示例非常好用,它不是为答案而创建的…)
儿童剃须刀
@inject NotifierService Notifier
@implements IDisposable
@inject IState State
<hr />
<input type="checkbox" @bind="State.ShowEasterEggs" />Show Easter Eggs
<hr />
<h1>User puts in something</h1>
<input type="text" @bind="@value" />
<button @onclick="@AddValue">Add value</button>
@foreach (var value in Notifier.ValuesList)
{
<p>@value</p>
}
@code {
private string value { get; set; }
public void AddValue()
{
Notifier.AddTolist(value);
}
public async Task OnNotify()
{
await InvokeAsync(() =>
{
StateHasChanged();
});
}
protected override void OnInitialized()
{
Notifier.Notify += OnNotify;
}
public void Dispose()
{
Notifier.Notify -= OnNotify;
}
}
@inject NotifierService Notifier
@implements IDisposable
@inject IState State
<hr />
@if (State.ShowEasterEggs)
{
<span>EASTER EGGS SHOWN</span>
}
<hr />
<h1>Displays Value from service and lets user put in new value</h1>
<input type="text" @bind="@value" />
<button @onclick="@AddValue">Set Value</button>
@code {
private string value { get; set; }
public void AddValue()
{
Notifier.AddTolist(value);
}
protected override void OnInitialized()
{
State.Notify += OnNotify;
}
public void OnNotify()
{
InvokeAsync(() =>
{
StateHasChanged();
});
}
public void Dispose()
{
State.Notify -= OnNotify;
}
}
NotifierService.cs
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading.Tasks;
using ChildComponentsCommunication.Shared;
using Microsoft.AspNetCore.Components;
namespace ChildComponentsCommunication
{
public class NotifierService
{
private readonly List<string> values = new List<string>();
public IReadOnlyList<string> ValuesList => values;
public NotifierService()
{
}
public async void AddTolist(string value)
{
values.Add(value);
if (Notify != null)
{
await Notify?.Invoke();
}
}
public event Func<Task> Notify;
}
}
IState.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace ChildComponentsCommunication
{
public interface IState
{
event Action Notify;
bool ShowEasterEggs { get; set; }
}
public class State : IState
{
public event Action Notify;
bool showEggs = false;
public bool ShowEasterEggs
{
get => showEggs;
set
{
if (showEggs != value)
{
showEggs = value;
if (Notify != null)
{
Notify?.Invoke();
}
}
}
}
}
}
services.AddSingleton<IState, State>();
services.AddScoped<NotifierService>();
希望这能奏效。。。