1

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.

3
  • I think one problem is that your API gets the data, but you never actually put it into the ObservableCollection that your View is looking at? So the data exists in your API service but the ViewModel's collection stays empty. Does that make sense. Does VMMeetman.Meetman = API.Meetman ever occur? Commented Aug 21 at 8:23
  • Good afternoon, I can't figure out how to do this (( How to pass data from the API to the collection, that's probably my question. If you could show me an example of a few lines of code, I could understand how this process works. Commented Aug 21 at 8:33
  • Let put it as an answer as this is not formatting well Commented Aug 21 at 8:36

1 Answer 1

1

Following on from my comments

It seems you get the API data but do nothing... from the code I see, so this is one solution for you.

There will be better solutions, depending on the bigger picture, i would recommend setting your service up as dependency injection. Hopefully this points you in the right direction

So on your PageModel, when you want to use this, you just need to do something like this

VMMeetman meetman = New VMMeetman() // Auto populates with the api data
public partial class VMMeetman : ObservableObject
{
    private readonly ApiServiceListUser api;
    
    public VMMeetman()
    {
        api = new ApiServiceListUser();
        meetmans = new ObservableCollection<Meetman>();        
        
        LoadData();
    }
  
    [ObservableProperty]
    private ObservableCollection<Meetman> meetmans;
    
    // I think you need something like this...
    private async void LoadData()
    {
        var data = await api.RefreshDataAsync();
        
        if (data != null)
        {
            foreach (var meetman in data)
            {
                Meetmans.Add(meetman);
            }
        }
    }
}

This is not intended to be the best answer just a guide*

Sign up to request clarification or add additional context in comments.

12 Comments

I can see that my database has a SELECT*FROM query for my Meetman table, but nothing appears in the View, and I'm trying to bind to the CarouselView.
Is your data populating when you do this VMMeetman meetman = New VMMeetman() // beakpoint the loaddata method and see
[0:] Connection failure: \tERROR {0}
If I understand correctly, is there an error in the HttpClient connection class?
> [0:] Connection failure: \tERROR {0} That appears to be an API issue- just keep debugging it, API too and you will find the issue
My asp net core api is running in parallel, and all methods return a positive response. GET returns the entire list, so I'll try to debug it in the client side in the connection class. It's quite a challenge.
I am unsure where the error is coming from, but if your asking its occurring inside this method, then yes RefreshDataAsync() The error could be the program or the API but something is incorrect. I would check your API calls and see if they work, if they do, then it most likely will the program
I put a breakpoint on the Uri line and got the following output: [WindowOnBackDispatcher] OnBackInvokedCallback is not enabled for the application. [WindowOnBackDispatcher] Set 'android:enableOnBackInvokedCallback="true"' in the application manifest.
You can ignore that, i dont think that is the issue. break point here Uri uri = new("10.0.2.2:5000/api/meetman/getall"); and step through each line, you should end up inside the catch and check what the exception is
The reference point, if (data != null), displays the result in the output: System.Not supported exception: The specified method is not supported.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.