You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

103 lines
2.2 KiB

---
sidebar_position: 7
title: Using the component
---
Now that our component is functional, we just have to use it, for that we just have to declare it in our page `Pages/Index.razor` with a fixed data.
## Add method in the data service
Open the interface of the service and add a new method for get the recipes.
```csharp title="Services/IDataService.cs"
public interface IDataService
{
Task Add(ItemModel model);
Task<int> Count();
Task<List<Item>> List(int currentPage, int pageSize);
Task<Item> GetById(int id);
Task Update(int id, ItemModel model);
Task Delete(int id);
// highlight-next-line
Task<List<CraftingRecipe>> GetRecipes();
}
```
## Add method to the local service
Open the local service and implement the new method for get the recipes.
```csharp title="Services/DataLocalService.cs"
public class DataLocalService : IDataService
{
...
public Task<List<CraftingRecipe>> GetRecipes()
{
var items = new List<CraftingRecipe>
{
new CraftingRecipe
{
Give = new Item { DisplayName = "Diamond", Name = "diamond" },
Have = new List<List<string>>
{
new List<string> { "dirt", "dirt", "dirt" },
new List<string> { "dirt", null, "dirt" },
new List<string> { "dirt", "dirt", "dirt" }
}
}
};
return Task.FromResult(items);
}
}
```
## Component declaration
```cshtml title="Pages/Index.razor"
<div>
<Crafting Items="Items" Recipes="Recipes" />
</div>
```
```csharp title="Pages/Index.razor.cs"
public partial class Index
{
[Inject]
public IDataService DataService { get; set; }
public List<Item> Items { get; set; } = new List<Item>();
private List<CraftingRecipe> Recipes { get; set; } = new List<CraftingRecipe>();
protected override async Task OnInitializedAsync()
{
await base.OnInitializedAsync();
Items = await DataService.List(0, await DataService.Count());
Recipes = await DataService.GetRecipes();
}
}
```
## Import JavaScript files
The component is displayed but the user actions are not displayed, quite simply because we have not imported the JavaScript file for it.
Open the `Pages/_Layout.cshtml` file and add the following script tag:
```cshtml title="Pages/_Layout.cshtml"
...
<script src="Components/Crafting.razor.js"></script>
...
```