user13714356
user13714356

Reputation: 171

Load Image Async from Api

I have a Blazor Server .Net 6 app. It has a Synfusion grid which has an ImageViewer componen that I have built. When the grid is loaded it passes a DocumentID to the ImageViewer for each row. The ImageViwer takes the DocumenID and loads an image via a web API service from a database. Teh problem I have is that the image does not fully load, it works if I use the OnInitializedAsync method but thsi does not work if I filter the data. Any ideads the best method to load such images

<SfGrid>
<MyImageViewer AuthCookieValue="@AuthCookieValue" DocumentID="@data.DocumentID" />
<SfGrid>

//THIS IS MY IMAGE CONTROL

@inject HttpClient httpClient

@if (DocumentFileData != null)
{
<img src="data:image;base64,@(Convert.ToBase64String(DocumentFileData))"  />
}


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

[Parameter] public string AuthCookieValue { get; set; }

[Parameter] public int DocumentID
{
    get { return _DocumentID; }

    set
    {
        _DocumentID = value;

        //I know this is naughty to call a method via a property and does not work but thought I would try to trigger the change of the image when I refresh the grid 
        Task.Run(() => GetDocument());
    }
}

private byte[] DocumentFileData { get; set; }

protected async override Task OnInitializedAsync()
{
    //THIS METHOD WORKS BUT DOES NOT WORK WHEN I CHANGE THE GRID
    if (DocumentID != 0)
    {
        await GetDocument();
    }
}


private async Task GetDocument()
{
    httpClient.DefaultRequestHeaders.Clear();
    httpClient.DefaultRequestHeaders.Add("Authorization", "Bearer " + AuthCookieValue);  
    MyServices.DocumentService documentService;documentService = new(httpClient);

    documentService = new(httpClient);
    DocumentModel doc = await documentService.GetDocumentAsync(_DocumentID);
    DocumentFileData = doc.FileData;

 }
}

enter image description here

Many thanks in advance

Upvotes: 1

Views: 714

Answers (1)

Henk Holterman
Henk Holterman

Reputation: 273179

Make two small changes:

// //I know this is naughty to call a method via a property and does not work but thought I would try to trigger the change of the image when I refresh the grid 
//  Task.Run(() => GetDocument());

and

//protected async override Task OnInitializedAsync()
  protected async override Task OnParametersSetAsync()
  {

See the Lifecycle events documentation.

OnInitializedAsync() is only called once in the lifetime of a component. OnParametersSetAsync() is called each time DocumentID changes, and the side benefit is that you don't need that Task.Run() anymore.

The fact that Task.Run() was not awaited here made your UI fall out of sync and not show the image. It was being loaded but not rendered.

Upvotes: 2

Related Questions