Home > Blockchain >  Blazor - call statehaschanged from service
Blazor - call statehaschanged from service

Time:12-04

how can call from OfferteService.cs to get a StateHasChanged function in detailsOfferta.razor?

hello how can I call the StateHasChanged function from a service to update the detailsOfferta.razor page by the function statehaschanged?

Thank you very much

I tried invokeasync but it does not work

CodePudding user response:

if you have a BlazorServer, then the state of your components-view is stored on the server. You can do so. Register the service as a scoped, this gives the service lifetime equal to your components, if the lifetime is needed more than the register how singleton. Declare an event in the service, in my case it is RX observable. Inject the service into the component and subscribe on event.

    public partial class YourComponent : IDisposable
    {
        private IDisposable _disposable = null;
        [Inject] public ITimerService TimerService { get; set; }
        public string Time { get; set; }

        protected override async Task OnInitializedAsync()
        {
            _disposable = TimerService.Times.Subscribe(OnTimeMessage);
        }

        private void OnTimeMessage(string time)
        {
            Time = time;
            StateHasChanged();
        }

        public void Dispose()
        {
            _disposable?.Dispose();
        }
    }

    public interface ITimeService
    {
        IObservable<string> Times { get; }
    }

    public class TimeService : ITimeService
    {
        private readonly Subject<string> _subject = new();
        private Timer _timer;

        public TimeService()
        {
            _timer = new Timer(() =>
            {
                _subject.OnNext(DateTime.UtcNow.ToString("G"));
            }, null, 1000, 1000);
        }

        public void Dispose()
        {
            _timer.Dispose();
            _subject.Dispose();
        }

        public void PublishError(string error)
        {
            _subject.OnNext(error);
        }

        public IObservable<string> Times()
        {
            return _subject;
        }
    }

// In host initialization            
//services.AddSingleton<ITimeService, TimeService>();
services.AddScoped<ITimeService, TimeService>();

CodePudding user response:

(How do I) call StateHasChanged from service

You don't.

What you need to implement is the Notification pattern.

Your data, and it's management, should reside in your service. When something changes in that service, a service level event is raised: this invokes any registeted handlers. Components that display data from the service register event handlers that call StateHasChanged when they are invoked.

This answer to a similar question describes how to build a notication service for the Blazor WeatherForecast - https://stackoverflow.com/a/69562295/13065781

  • Related