Skip to content

Instantly share code, notes, and snippets.

@danielplawgo
Created May 25, 2019 04:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save danielplawgo/c3349da38619c04c298b16cdf53cd4f0 to your computer and use it in GitHub Desktop.
Save danielplawgo/c3349da38619c04c298b16cdf53cd4f0 to your computer and use it in GitHub Desktop.
Blazor użycie Web API
@layout MainLayout
@using ApiDemo.Shared
@using ApiDemo.Client.Services
@page "/fetchdata"
@inject IWeatherForecastService Service
<h1>Weather forecast</h1>
<p>This component demonstrates fetching data from the server.</p>
@if (forecasts == null)
{
<p><em>Loading...</em></p>
}
else
{
<table class="table">
<thead>
<tr>
<th>Date</th>
<th>Temp. (C)</th>
<th>Temp. (F)</th>
<th>Summary</th>
</tr>
</thead>
<tbody>
@foreach (var forecast in forecasts)
{
<tr>
<td>@forecast.Date.ToShortDateString()</td>
<td>@forecast.TemperatureC</td>
<td>@forecast.TemperatureF</td>
<td>@forecast.Summary</td>
</tr>
}
</tbody>
</table>
}
@functions {
WeatherForecast[] forecasts;
protected override async Task OnInitAsync()
{
forecasts = await Service.GetAsync();
}
}
[Route("api/[controller]")]
public class SampleDataController : Controller
{
private static string[] Summaries = new[]
{
"Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
};
[HttpGet("[action]")]
public IEnumerable<WeatherForecast> WeatherForecasts()
{
var rng = new Random();
return Enumerable.Range(1, 5).Select(index => new WeatherForecast
{
Date = DateTime.Now.AddDays(index),
TemperatureC = rng.Next(-20, 55),
Summary = Summaries[rng.Next(Summaries.Length)]
});
}
}
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddScoped<IWeatherForecastService, WeatherForecastService>();
}
public void Configure(IComponentsApplicationBuilder app)
{
app.AddComponent<App>("app");
}
}
public class WeatherForecast
{
public DateTime Date { get; set; }
public int TemperatureC { get; set; }
public string Summary { get; set; }
public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);
}
public class WeatherForecastService : IWeatherForecastService
{
private readonly HttpClient _client;
public WeatherForecastService(HttpClient client)
{
_client = client;
}
public async Task<WeatherForecast[]> GetAsync()
{
return await _client.GetJsonAsync<WeatherForecast[]>("api/SampleData/WeatherForecasts");
}
}
public interface IWeatherForecastService
{
Task<WeatherForecast[]> GetAsync();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment