Search code examples
razorcomponentshttpclientblazorwebassembly

How to consume Web API OnInitialized in Blazor Child Component?


I'm new to C# and Blazor WASM in general and have struggled with this for quite some time.

I have a parent component "Parent.razor" and child component "Child.razor"

In parents, apart from all other HTML stuff, I also have child tag. So it looks something like (just for example)

Parent.razor
@page "/machines"

<h1>Machine Information<h1>
<child></child>

@code
{
}

Now, there is a foreach loop in child component that iterate each item in a list (machinetypes) If machinetypes is from a specified static list, it all works well. Screenshot for reference, I am able to get the dropdown that I want

Code below.

Child.razor
@using Namespace.Shared.Models
@using Blazorise
@inject HttpClient Http


<select>
    @foreach (var machinetype in machinetypes)
    {
        <option value="@machinetype.MachineTypeId">@machinetype.MachineTypeName</option>
    }
</select>

@code {
    public int amachinetypeid { get; set; }

    //This works
    MachineType[] machinetypes = new MachineType[]
    {
        new MachineType{MachineTypeName="TypeX"},
        new MachineType{MachineTypeName="TypeY"}
    };
}

But when I try to consume web API (that also returns list), it doesn't work. The page loads indefinitely and I will encounter and error. Code below.

Child.razor
@using Namespace.Shared.Models
@using Blazorise
@inject HttpClient Http


<select>
    @foreach (var machinetype in machinetypes)
    {
        <option value="@machinetype.MachineTypeId">@machinetype.MachineTypeName</option>
    }
</select>

@code {
public int amachinetypeid { get; set; }
public MachineType[] machinetypes;

//This works
//MachineType[] machinetypes = new MachineType[]
//{
//   new MachineType{MachineTypeName="TypeX"},
//    new MachineType{MachineTypeName="TypeY"}
//};

//This does not work    
protected override async Task OnInitializedAsync()
{
    machinetypes = await Http.GetJsonAsync<MachineType[]>("api/machinetype/");
}

}

Quick check on my web API, accessing it directly returns this to me. So it works alright. Click here to see screenshot of web API results

Could anyone advise what I did wrong? And is necessary to create an dependency injection a necessity to do this? If yes, could anyone please point me to a right direction?

Thank you in advance.


Solution

  • You are probably having a null-reference error. That might look like "loads indefinitely".

    What you need is

    public MachineType[] machinetypes = new MachineType[0];