Search code examples
c#blazorblazor-server-sideblazor-component

How do I instantiate a C# service and use its data in a Blazor component


I am using Blazor and I am a beginner.

Currently I have several Blazor components that all need the same JSON data (data fetched from one URL, e.g., http://localhost/todo)

Instead of fetching the same URL inside all my components and duplicating my code, I decided to create a Service that fetchs the URL and share this service's output accross my components.

Here is the service, and all it does fetch a URL and return a JSON object (at least that is what I am trying to do)

using TodoApp.Models.TodoTestModel;
using Newtonsoft.Json;
using System.Net.Http.Headers;

namespace Todo.Services
{
    public class Todo 
    {
        public string TodoURL { get; set; }
        public object result { get; set; }

        async public Task<object> TodoTypes()
        {
            using (HttpClient client = new HttpClient())
            {
                // HTTP header stuff

                HttpResponseMessage response = client.GetAsync(TodoURL).Result;
                response.EnsureSuccessStatusCode();
                string responseData = await response.Content.ReadAsStringAsync();
                result = JsonConvert.DeserializeObject<TodoTestModel>(responseData);

                return result;

            }

        }
    }
    }
}

The idea is call this service and give my components the output as

<TodoComponent ToDoResult="@result"> </ToDoComponent>

But I am having a problem when instanciating the object, e.g,:

@page "/"
@using TodoApp.Services;  
@inject TodoApp.Services.Todo Todo; 


<h5> List of todos </h5>


@code {
    Todo td = new Todo(); 
    td.TodoURL = ".." // does not work
}

In short I am trying to do the following:

  • Instanciate the class
  • Provide it a URL
  • Get the JSON data (result) to pass it into my TodoComponent

Thanks for the help


Solution

  • vaeon you can directly use client.GetJsonAsync and avoid the deserialization step in Vikram's example.The returned result set is not matching with the expected typeof List.

          var response = await client.GetFromJsonAsync(TodoURL);       
          return response;