在Blazor的两个子组件之间共享数据的最佳方法

时间:2020-05-27 11:22:12

标签: c# .net-core blazor blazor-client-side asp.net-blazor

我有这个代码。

<ParentComponent>
    <ChildComponet>
         @renderFragment
    </ChildComponent>
    <ChildComponetn>
       <GridComponent Data="@dataList"/>
    </ChildComponent>
</ParentComponent>

其中@renderFragment是动态呈现组件,而Grid compone是具有“添加新”,“编辑记录”,“删除”等操作的某些数据的列表。

如果单击“添加新”,则会在@renderFragment中动态打开用于添加新记录的表单,我们希望在提交表单后刷新网格数据,但是我们不知道如何在两个子组件之间共享某些数据。编辑表单也一样,当编辑某些记录时,我们需要刷新网格组件以显示编辑的数据。 如果需要更多代码和数据,请发表评论。

2 个答案:

答案 0 :(得分:4)

您可以定义一个实现State模式和Notifier模式的类服务,以处理对象的状态,将状态传递给对象并通知订户对象更改。

这是此类服务的简化示例,它使父组件能够与他的孩子进行通信。

NotifierService.cs

public class NotifierService
{
    private readonly List<string> values = new List<string>();
    public IReadOnlyList<string> ValuesList => values;

    public NotifierService()
    {

    }

    public async Task AddTolist(string value)
    {
        values.Add(value);
        if (Notify != null)
        {
            await Notify?.Invoke();
        }

    }

    public event Func<Task> Notify;
 }

Child1.razor

 @inject NotifierService Notifier
 @implements IDisposable

 <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 async Task AddValue()
    {
        await Notifier.AddTolist(value);
    }

    public async Task OnNotify()
   {
      await InvokeAsync(() =>
      {
        StateHasChanged();
      });
   }


  protected override void OnInitialized()
  {
     Notifier.Notify += OnNotify;
  }


   public void Dispose()
   {
       Notifier.Notify -= OnNotify;
   }
}

Child2.razor

@inject NotifierService Notifier

<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 async Task AddValue()
   {
      await Notifier.AddTolist(value);

   }

 }

用法

 @page "/"

 <Child1></Child1>
 <Child2></Child2>

Startup.ConfigureServices

services.AddScoped<NotifierService>();

希望这对您有帮助...

答案 1 :(得分:0)

有几种方法可以做到,我只是使用Singleton类学习了一种非常酷的方法。

我有这个组件,可以用来在聊天中向其他用户发送消息,称为SubscriptionService,但是您可以使用任何类。

将此注入添加到您的两个组件中:

@inject Services.SubscriberService SubscriberService



#region using statements

using DataJuggler.UltimateHelper.Core;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Transactions;

#endregion

namespace BlazorChat.Services
{

    #region class SubscriberService
    /// <summary>
    /// This class is used to subscribe to services, so other windows get a notification a new message 
    /// came in.
    /// </summary>
    public class SubscriberService
    {

        #region Private Variables
        private int count;
        private Guid serverId;
        private List<SubscriberCallback> subscribers;
        #endregion

        #region Constructor
        /// <summary>
        /// Create a new instance of a 'SubscriberService' object.
        /// </summary>
        public SubscriberService()
        {
            // Create a new Guid
            this.ServerId = Guid.NewGuid();
            Subscribers = new List<SubscriberCallback>();
        }
        #endregion

        #region Methods

            #region BroadcastMessage(SubscriberMessage message)
            /// <summary>
            /// This method Broadcasts a Message to everyone that ins't blocked.
            /// Note To Self: Add Blocked Feature
            /// </summary>
            public void BroadcastMessage(SubscriberMessage message)
            {
                // if the value for HasSubscribers is true
                if ((HasSubscribers) && (NullHelper.Exists(message)))
                {   
                    // Iterate the collection of SubscriberCallback objects
                    foreach (SubscriberCallback subscriber in Subscribers)
                    {
                        // if the Callback exists
                        if ((subscriber.HasCallback) && (subscriber.Id != message.FromId))
                        {
                            // to do: Add if not blocked

                            // send the message
                            subscriber.Callback(message);
                        }
                    }
                }
            }
            #endregion

            #region GetSubscriberNames()
            /// <summary>
            /// This method returns a list of Subscriber Names ()
            /// </summary>
            public List<string> GetSubscriberNames()
            {
                // initial value
                List<string> subscriberNames = null;

                // if the value for HasSubscribers is true
                if (HasSubscribers)
                {
                    // create the return value
                    subscriberNames = new List<string>();

                    // Get the SubscriberNamesl in alphabetical order
                    List<SubscriberCallback> sortedNames = Subscribers.OrderBy(x => x.Name).ToList();

                    // Iterate the collection of SubscriberService objects
                    foreach (SubscriberCallback subscriber in sortedNames)
                    {
                        // Add this name
                        subscriberNames.Add(subscriber.Name);
                    }
                }

                // return value
                return subscriberNames;
            }
            #endregion

            #region Subscribe(string subscriberName)
            /// <summary>
            /// method returns a message with their id
            /// </summary>
            public SubscriberMessage Subscribe(SubscriberCallback subscriber)
            {
                // initial value
                SubscriberMessage message = null;

                // If the subscriber object exists
                if ((NullHelper.Exists(subscriber)) && (HasSubscribers))
                {
                    // Add this item
                    Subscribers.Add(subscriber);    

                    // return a test message for now
                    message = new SubscriberMessage();

                    // set the message return properties
                    message.FromName = "Subscriber Service";
                    message.FromId = ServerId;
                    message.ToName = subscriber.Name;
                    message.ToId = subscriber.Id;
                    message.Data = Subscribers.Count.ToString();
                    message.Text = "Subscribed";
                }

                // return value
                return message;
            }
            #endregion

            #region Unsubscribe(Guid id)
            /// <summary>
            /// This method Unsubscribe
            /// </summary>
            public void Unsubscribe(Guid id)
            {
                // if the value for HasSubscribers is true
                if ((HasSubscribers) && (Subscribers.Count > 0))
                {
                    // attempt to find this callback
                    SubscriberCallback callback = Subscribers.FirstOrDefault(x => x.Id == id);

                    // If the callback object exists
                    if (NullHelper.Exists(callback))
                    {
                        // Remove this item
                        Subscribers.Remove(callback);

                         // create a new message
                        SubscriberMessage message = new SubscriberMessage();

                        // set the message return properties
                        message.FromId = ServerId;
                        message.FromName = "Subscriber Service";
                        message.Text = callback.Name + " has left the conversation.";
                        message.ToId = Guid.Empty;
                        message.ToName = "Room";

                        // Broadcast the message to everyone
                        BroadcastMessage(message);
                    }
                }
            }
            #endregion

        #endregion

        #region Properties

            #region Count
            /// <summary>
            /// This property gets or sets the value for 'Count'.
            /// </summary>
            public int Count
            {
                get { return count; }
                set { count = value; }
            }
            #endregion

            #region HasSubscribers
            /// <summary>
            /// This property returns true if this object has a 'Subscribers'.
            /// </summary>
            public bool HasSubscribers
            {
                get
                {
                    // initial value
                    bool hasSubscribers = (this.Subscribers != null);

                    // return value
                    return hasSubscribers;
                }
            }
            #endregion

            #region ServerId
            /// <summary>
            /// This property gets or sets the value for 'ServerId'.
            /// </summary>
            public Guid ServerId
            {
                get { return serverId; }
                set { serverId = value; }
            }
            #endregion

            #region Subscribers
            /// <summary>
            /// This property gets or sets the value for 'Subscribers'.
            /// </summary>
            public List<SubscriberCallback> Subscribers
            {
                get { return subscribers; }
                set { subscribers = value; }
            }
            #endregion

        #endregion

    }
    #endregion

}

对于我的聊天应用程序,我希望它可用于所有实例,因此在Startup.cs的configure services方法中,添加一个Sington:

services.AddSingleton<SubscriberService>();

使其仅对此浏览器实例可用:

services.AddScoped(SubscriberService);

现在,从这两个组件中,您都可以调用方法或访问注入类的属性:

SubscriptionService.GetSubscribers();

或者,如果您更喜欢界面,我写了一篇有关此的博客文章,我不想复制文本:

https://datajugglerblazor.blogspot.com/2020/01/how-to-use-interfaces-to-communicate.html

但是,注入方式非常酷,因为您的整个应用程序可以与其他用户实例进行通讯以进行聊天。