Quantcast
Channel: Active questions tagged blazor - Stack Overflow
Viewing all articles
Browse latest Browse all 4839

What is the best way to poll data from an API in Blazor server on .NET 8?

$
0
0

I have a Blazor component that will be reused, the parameters in it will point to specific endpoints that are specified when the component is created. These components all need to be polling data constantly (every few seconds) as the API that I'm calling does not support streaming data. The data from these, very small just a JSON response with few elements, need to be displayed and updated on the frontend.

I'm having a hard time implementing this into my project, I'm trying to use IHostedService that consumes a separate scoped service that reaches out to the api specified by the respective component. But all of the docs I've seen from Microsoft and examples online show them doing something trivial like printing, nothing being returned.

Is this the right way to go about doing this? I've gotten this to work by just setting up a timer in the .razor page and making the scoped service a singleton. However, once the service is scoped I get the exception

Cannot access a disposed object

on the HttpClient.

.razor component code

protected override async Task OnInitializedAsync(){    // Set up polling every 5 seconds    timer = new Timer(async _ => await FetchData(), null, 0, 5000);}private async Task FetchData(){    variable = await scopedservice.GetData(info);    await InvokeAsync(() => StateHasChanged()); }

Scoped service:

public async Task<Data> GetData(string info){        try        {            return await _httpClient.GetFromJsonAsync<Data>($"{info}");        }        catch (Exception ex)        {            Debug.WriteLine(ex);            return default;        }}

Program.cs:

builder.Services.AddHttpClient();builder.Services.AddScoped<IScopedService, ScopedService>();

Viewing all articles
Browse latest Browse all 4839

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>