I have an API service class that implements HttpClient to connect to my API, I have a user list model, and I have a View Model using the Community Toolkit MVVM approach. I would like to understand how these three components are related and how to connect them so that my View can receive data.
In the API service class, I specified the following:
public class ApiServiceListUser
{
private static HttpClient client;
private static JsonSerializerOptions options;
public List<Meetman>? Meetmans { get; set; }
public ApiServiceListUser()
{
client = new HttpClient();
options = new JsonSerializerOptions()
{
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
WriteIndented = true,
};
}
public async Task<List<Meetman>> RefreshDataAsync()
{
Meetmans = [];
Uri uri = new("http://10.0.2.2:5000/api/meetman/getall");
try
{
HttpResponseMessage response = await client.GetAsync(uri);
if (response.IsSuccessStatusCode)
{
string content = await response.Content.ReadAsStringAsync();
Meetmans = JsonSerializer.Deserialize<List<Meetman>>(content, options);
}
}
catch (Exception ex)
{
Debug.WriteLine(@"\tERROR {0}", ex.Message);
}
return Meetmans;
}
}
}
In my View Model, I specified:
public partial class VMMeetman : ObservableObject
{
private readonly ApiServiceListUser client;
public VMMeetman()
{
ApiServiceListUser api = new();
meetmans = [];
}
[ObservableProperty]
private ObservableCollection<Meetman> meetmans;
[ObservableProperty]
private int _meetmanId;
[ObservableProperty]
private string _iname;
[ObservableProperty]
private string _sname;
[ObservableProperty]
private string _tname;
[ObservableProperty]
private string _location;
I expected my API to pass data to my Meetman model, then I called the observable collection of user list in my View Model and I think it received it, then I registered my View Model as a service and declared it on my page where the Carousel View control is located, and I specified the binding to Meetmans from my View Model. I expected my Carousel View control to receive a list of users from my database through my API, but it doesn't happen.
Where am I wrong and what is the correct approach? My API is tested for requests and returns lists and (or) makes a database entry, so there are no errors on the backend side.