要解决"Asp.Net Core SignalR + Angular 6问题",您可以按照以下步骤进行操作:
dotnet add package Microsoft.AspNetCore.SignalR
在Angular项目中,使用以下命令安装SignalR客户端软件包:
npm install @aspnet/signalr
using Microsoft.AspNetCore.SignalR;
namespace YourNamespace
{
public class ChatHub : Hub
{
public async Task SendMessage(string user, string message)
{
await Clients.All.SendAsync("ReceiveMessage", user, message);
}
}
}
services.AddSignalR();
并在Configure方法中添加以下代码:
app.UseSignalR(routes =>
{
routes.MapHub("/chatHub");
});
import { Injectable } from '@angular/core';
import * as signalR from '@aspnet/signalr';
@Injectable({
providedIn: 'root'
})
export class SignalRService {
private hubConnection: signalR.HubConnection;
constructor() {
this.hubConnection = new signalR.HubConnectionBuilder()
.withUrl('http://localhost:5000/chatHub')
.build();
}
public startConnection() {
this.hubConnection.start()
.then(() => console.log('Connection started'))
.catch(err => console.log('Error while starting connection: ' + err));
}
public addMessageListener(callback: (user: string, message: string) => void) {
this.hubConnection.on('ReceiveMessage', callback);
}
public sendMessage(user: string, message: string) {
this.hubConnection.invoke('SendMessage', user, message)
.catch(err => console.error(err));
}
}
import { Component, OnInit } from '@angular/core';
import { SignalRService } from './signalr.service';
@Component({
selector: 'app-chat',
templateUrl: './chat.component.html',
styleUrls: ['./chat.component.css']
})
export class ChatComponent implements OnInit {
constructor(private signalRService: SignalRService) { }
ngOnInit() {
this.signalRService.startConnection();
this.signalRService.addMessageListener((user, message) => {
console.log(`Received message from ${user}: ${message}`);
});
}
sendMessage(user: string, message: string) {
this.signalRService.sendMessage(user, message);
}
}
{{message}}
这些步骤将帮助您在Asp.Net Core SignalR和Angular 6之间建立一个简单的聊天应用程序。您可以根据需要进行调整和扩展。