【问题标题】:Load Image Async from Api从 Api 异步加载图像
【发布时间】:2022-11-16 22:04:12
【问题描述】:

我有一个 Blazor Server .Net 6 应用程序。它有一个 Synfusion 网格,其中有一个我构建的 ImageViewer 组件。加载网格时,它会将每行的 DocumentID 传递给 ImageViewer。 ImageViwer 获取 DocumenID 并通过 Web API 服务从数据库加载图像。我遇到的问题是图像没有完全加载,如果我使用 OnInitializedAsync 方法它可以工作,但是如果我过滤数据则它不起作用。任何想法加载此类图像的最佳方法

<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;

 }
}

提前谢谢了

【问题讨论】:

  • “当我更改网格时不起作用”是什么意思?
  • 还有你是如何过滤数据的?你能分享所有的 Sfgrid 代码吗
  • 嗨@WajeehHasan 当然 - 请参阅我的过滤器如何工作的附件图片。它实际上是一个带有按钮的表单。我根据过滤器点击数据库获取新数据,但是当我通过网格向它们提供 DocumentID 时,图像被加载了。我使用这种方法是因为我不想在原始数据库调用中包含图像二进制数据。例如,我的过滤器返回 100 辆汽车,但我的网格被分页以仅显示 10 个结果。因此,而不是将图像二进制数据包含在 100 个结果集中。网格将通过 API 调用加载显示的 10 个结果的图像。如果您需要更多信息,请告诉我

标签: asp.net-web-api async-await blazor blazor-server-side


【解决方案1】:

做两个小改动:

// //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());

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

请参阅 Lifecycle events 文档。

OnInitializedAsync() 在组件的生命周期中只被调用一次。每次 DocumentID 更改时都会调用 OnParametersSetAsync(),附带的好处是您不再需要 Task.Run() 了。

此处未等待 Task.Run() 的事实使您的 UI 不同步并且不显示图像。它正在加载但未呈现。

【讨论】:

  • 天哪,你绝对是明星。那很有用。我不知道有 OnParametersSetAsync 事件。这真太了不起了。非常感谢您的帮助。你是一个绝对的绅士。真的很感激
  • 很高兴它有所帮助。作为提问者,您可以“接受”答案,以便其他人可以快速看到有一个有效的解决方案。
猜你喜欢
  • 2016-02-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多