我根本无法弄清楚如何从 Angular 建立信号器连接。
在https://docs.microsoft.com/en-us/aspnet/signalr/overview/getting-started/tutorial-getting-started-with-signalr-and-mvc使用以下教程
我SignalR
在 vs2017 中的现有 .Net 4.6 解决方案中添加了一个新的 2.4.0 项目。
我还有一个Angular 7
应用程序,我SignalR
通过它添加了包npm install @aspnet/signalr
现在我试图在客户端和服务器之间建立一个简单的连接,但不知道如何建立初始连接。
我的前端不断抛出异常:
core.js:15714 ERROR Error: Uncaught (in promise): Error: Cannot send data if the connection is not in the 'Connected' State.
错误:如果连接未处于“已连接”状态,则无法发送数据。
在我的前端搜索组件中,我添加了一些用于测试的字段:
<mat-form-field>
<input matInput placeholder="message" [(ngModel)]="message">
</mat-form-field>
<button mat-button type="button" (click)="sendMessageToServer()"><span>Send</span></button>
<p *ngFor="let m of messages">{{m}}</p>
在我的 ts 文件中:
// import other components/services here..
import { HubConnection, HubConnectionBuilder} from '@aspnet/signalr';
@Component({
selector: 'app-my-search',
templateUrl: './my-search.component.html',
styleUrls: ['./my-search.component.scss']
})
export class MySearchComponent implements OnInit {
public hubConnection: HubConnection;
public messages: string[] = [];
public message: string;
constructor() { }
ngOnInit() {
// SIGNALR MESSAGE HUB
let builder = new HubConnectionBuilder();
this.hubConnection = builder.withUrl('/SynBroadcastHub/BroadcastMessage').build(); // see startup.cs
this.hubConnection.on('notifyUser', (message) => {
this.messages.push(message);
console.log(message);
});
this.hubConnection.start();
}
// signalr, send msg from client
sendMessageToServer() {
this.hubConnection.invoke('MessageToServer', this.message);
this.message = '';
}
}
在 c# 方面,我添加了一个SignalR Hub Class (v2)
文件 BroadcastHub.cs
using Microsoft.AspNet.SignalR;
namespace SynBroadcastHub
{
public class BroadcastHub : Hub
{
/// Message to client
public void BroadcastMessage(string data)
{
Clients.Caller.notifyUser(data);
}
/// Message from client application; broadcast to all clients if requested.
public void MessageToServer(string data, bool notifyAllClients = false)
{
if (notifyAllClients)
{
Clients.All.NotifyAllClients(data);
}
}
}
}
以及一个Startup.cs
文件:
using Microsoft.Owin;
using Microsoft.AspNet.SignalR;
using Owin;
[assembly: OwinStartup(typeof(SynBroadcastHub.Startup))]
namespace SynBroadcastHub
{
public class Startup
{
public void Configuration(IAppBuilder app)
{
HubConfiguration cfg = new HubConfiguration();
app.MapSignalR<PersistentConnection>("BroadcastHub/BroadcastMessage");
app.MapSignalR(cfg);
app.MapSignalR();
//app.MapSignalR<NotifyHub>("notify"); ???
}
public override Task OnDisconnected(bool stopCalled)
{
return Clients.All.leave(Context.ConnectionId, System.DateTime.Now.ToString());
}
public override Task OnConnected()
{
return Clients.All.joined(Context.ConnectionId, DateTime.Now.ToString());
}
public override Task OnReconnected()
{
return Clients.All.rejoined(Context.ConnectionId, DateTime.Now.ToString());
}
}
}