728x90
728x170

Service 를 하나 만들어 데이터를 가져와 화면에 바인딩하는 방법입니다.
Servie 에서 DB 에서 데이터를 가져오게 되는데 여기서는 임의로 만든 데이터를 반환하여 처리합니다.

PizzaService 를 만들고 등록합니다.

PizzaService.cs

using Blazor.AppTest.Data;

namespace Blazor.AppTest.Services
{
    public class PizzaService
    {
        public Task<PizzaItem[]> GetPizzasAsync()
        {
            // Get DB Data
            PizzaItem[] pizzaItems = new PizzaItem[3];
            pizzaItems[0] = new PizzaItem() { PizzaId = 1, Name = "마스터 트리플 코드", Description = "디저트로 즐기는 피자", Price = 28000, Vegan = true, Vegetarian = true };
            pizzaItems[1] = new PizzaItem() { PizzaId = 2, Name = "치즈 퐁듀 파이어 미트", Description = "씨푸드 퐁듀 피자의 귀환", Price = 29000, Vegan = true, Vegetarian = true };
            pizzaItems[2] = new PizzaItem() { PizzaId = 3, Name = "블로버스터4", Description = "4개 도시의 프리미엄 요리를 품은 피자", Price = 29000, Vegan = true, Vegetarian = true };

            return Task.FromResult<PizzaItem[]>(pizzaItems);
        }
    }
}

Program.cs 에서 PizzaService 등록

// Register the pizzas service
builder.Services.AddSingleton<PizzaService>();

화면에서 PizzaService 를 Inject 하여 사용

@page "/pizzas"
@using Blazor.AppTest.Data
@using Blazor.AppTest.Services

@inject PizzaService PizzaSvc

<h3>Pizza</h3>

@if (todaysPizzas == null)
{
    <p>We're finding out what pizzas are available today...</p>
}
else
{
    <table>
        <thead>
            <tr>
                <th>| Pizza Name </th>
                <th>| Description </th>
                <th>| Vegetarian </th>
                <th>| Vegan </th>
                <th>| Price | </th>
            </tr>
        </thead>
        <tbody>
            @foreach (var pizza in todaysPizzas)
            {
                <tr>
                    <td>@pizza.Name</td>
                    <td>@pizza.Description</td>
                    <td>@pizza.Vegetarian</td>
                    <td>@pizza.Vegan</td>
                    <td>@pizza.Price</td>
                </tr>
            }
        </tbody>
    </table>
}

@code {
    private PizzaItem[]? todaysPizzas;

    protected override async Task OnInitializedAsync()
    {
        todaysPizzas = await PizzaSvc.GetPizzasAsync();
    }
}

등록된 PizzaService 는 @inject PizzaService PizzaSvc 이렇게 선언하여(종속성 삽입) 어떤 화면에서든 사용이 가능합니다.

실행결과

[Source]
https://github.com/kei-soft/Blazor.AppTest

728x90
그리드형
Posted by kjun
,