@page "/"
@using LiveChat.Models;
@using Microsoft.AspNetCore.SignalR.Client
@inject NavigationManager Navigation
@implements IAsyncDisposable
LiveChat app
Sortert fra topp-bunn
@if (msgs != null)
{
@foreach (var message in msgs)
{
@message
}
} else
{
Ingen meldinger tilgjengelig.
}
@code {
private HubConnection? hubConnection;
private MessageModel messageModel = new MessageModel() { User = "", Message = "" };
private List msgs = new List();
protected override async Task OnInitializedAsync()
{
Console.WriteLine(messageModel);
hubConnection = new HubConnectionBuilder()
.WithUrl(Navigation.ToAbsoluteUri("/chathub"))
.Build();
using (var db = new ChattingContext())
{
var messages = db.Messages.ToList();
foreach (var msg in messages)
{
var encodedMsg = $"{msg.User}: {msg.Message}";
msgs.Add(encodedMsg);
InvokeAsync(StateHasChanged);
}
}
hubConnection.On("ReceiveMessage", (user, message) => {
var encodedMsg = $"{user}: {message}";
msgs.Add(encodedMsg);
InvokeAsync(StateHasChanged);
});
await hubConnection.StartAsync();
}
private async Task HandleSubmit()
{
if (hubConnection is not null)
{
await hubConnection.SendAsync("SendMessage", messageModel.User, messageModel.Message);
}
}
public bool IsConnected =>
hubConnection?.State == HubConnectionState.Connected;
public async ValueTask DisposeAsync()
{
if (hubConnection is not null)
{
await hubConnection.DisposeAsync();
}
}
}