85 lines
2.3 KiB
Plaintext
85 lines
2.3 KiB
Plaintext
@page "/fetchdata"
|
|
|
|
@using Blazor3State.Data
|
|
@using System.IO
|
|
|
|
@inject IHttpClientFactory httpClientFactory
|
|
|
|
<h1>Showing states in blazor</h1>
|
|
|
|
<p>This component demonstrates fetching data from a service.</p>
|
|
|
|
<button class="btn btn-primary" @onclick="LoadImage">New Image</button>
|
|
<div class="image-container">
|
|
<LoadingContainer State="@state">
|
|
<Loading>
|
|
<div class="lds-default"><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div></div>
|
|
</Loading>
|
|
<Loaded>
|
|
<img src="@imageData" alt="Alternate text" />
|
|
</Loaded>
|
|
<ErrorContent>
|
|
<p><em>An error has occurred. Click new image to try again !</em></p>
|
|
</ErrorContent>
|
|
</LoadingContainer>
|
|
</div>
|
|
|
|
@code {
|
|
Random random = new Random();
|
|
LoadingContainerState state;
|
|
string imageData;
|
|
|
|
protected override async Task OnInitializedAsync()
|
|
{
|
|
await LoadImage();
|
|
}
|
|
|
|
//async Task LoadImage()
|
|
//{
|
|
// state = LoadingContainerState.Loading;
|
|
// await Task.Delay(2000);
|
|
// if (random.Next(3) == 2)
|
|
// {
|
|
// state = LoadingContainerState.Error;
|
|
// }
|
|
// else state = LoadingContainerState.Loaded;
|
|
|
|
//}
|
|
|
|
async Task LoadImage()
|
|
{
|
|
state = LoadingContainerState.Loading;
|
|
await Task.Delay(2000);
|
|
|
|
var request = new HttpRequestMessage(HttpMethod.Get, "https://loremflickr.com/400/500");
|
|
|
|
var client = httpClientFactory.CreateClient();
|
|
|
|
var response = await client.SendAsync(request);
|
|
|
|
if (response.IsSuccessStatusCode)
|
|
{
|
|
using var responseStream = await response.Content.ReadAsStreamAsync();
|
|
var header = response.Content.Headers.FirstOrDefault(x => x.Key == "Content-Type");
|
|
string imageType = header.Value.First();
|
|
|
|
string encodedImage;
|
|
using (MemoryStream m = new MemoryStream())
|
|
{
|
|
responseStream.CopyTo(m);
|
|
byte[] imageBytes = m.ToArray();
|
|
encodedImage = Convert.ToBase64String(imageBytes);
|
|
}
|
|
|
|
imageData = $"data:{imageType};base64,{encodedImage}";
|
|
state = LoadingContainerState.Loaded;
|
|
|
|
}
|
|
else
|
|
state = LoadingContainerState.Error;
|
|
}
|
|
|
|
|
|
|
|
}
|