我能够连接到集线器,并且已连接OnConnected和OnDisconnected。他们应该从整数中进行加/减,并使用新值调用客户端回调。 我的角度应用程序已成功连接到服务器,但未触发我注册的回调函数。
这是我的Serverhub:
[HubName("online")]
public class OnlineHub : Hub
{
private static int userCount = 0;
public override Task OnConnected()
{
userCount++;
Clients.All.listUpdated(userCount);
return base.OnConnected();
}
public override Task OnDisconnected(bool stopCalled)
{
userCount--;
Clients.All.listUpdated(userCount);
return base.OnDisconnected(stopCalled);
}
}
这是我的Angular SignalRService:
import { AppSettings } from './../app.settings';
import { EventEmitter, Injectable, OnDestroy } from '@angular/core';
declare const $: any;
@Injectable()
export class SignalRService {
// Declare the variables
private onlineHub: any;
// create the Event Emitter
public messageReceived: EventEmitter<any>;
public connectionEstablished: EventEmitter<Boolean>;
public connectionExists: Boolean;
constructor(private appSettings: AppSettings) {
// Setup
this.connectionEstablished = new EventEmitter<Boolean>();
this.messageReceived = new EventEmitter<any>();
this.connectionExists = false;
}
// This method gets executed from angular controller
public initialize(proxyName: string): void {
this.onlineHub = $.connection.online;
this.onlineHub.client.listUpdated = function(list: any): void {
console.log(list);
this.messageReceived.emit(list);
};
this.startConnection();
}
private startConnection(): void {
$.connection.hub.url = this.appSettings.SIGNALR_BASE_URL + '/signalr';
$.connection.hub.start()
.done((data: any) => {
console.log('SignalR Connected with: ' + data.transport.name);
this.connectionEstablished.emit(true);
this.connectionExists = true;
})
.fail((error: any) => {
console.log('SignalR could not connect: ' + error);
this.connectionEstablished.emit(false);
});
}
private registerOnServerEvents() {
this.onlineHub.client.listUpdated = function(list: any): void {
console.log(list);
this.messageReceived.emit(list);
};
}
}
我按照文档所述在运行start()之前注册了我的回调“ listUpdated”,并且$ .connection.hub包含在调用start()之前的client.listUpdated,因此它应该注册。但是,仍然不会调用OnConnected方法。
答案 0 :(得分:1)
我通过将try / catch块中的OnConnected()和OnDisconnected()代码括起来并解决了此问题,并创建了一个称为“错误”的客户端方法,该方法将最终的异常返回给客户端。这样,我发现自己遇到了Json序列化问题。
我的集线器现在看起来像这样:
[HubName("online")]
public class OnlineHub : Hub
{
private static int userCount = 0;
public override Task OnConnected()
{
try
{
userCount++;
Clients.All.listUpdated(userCount);
}
catch (Exception exc)
{
Clients.All.error(exc);
}
return base.OnConnected();
}
public override Task OnDisconnected(bool stopCalled)
{
try
{
userCount--;
Clients.All.listUpdated(userCount);
}
catch (Exception exc)
{
Clients.All.error(exc);
}
return base.OnDisconnected(stopCalled);
}
}
在调用start()之前,我在js客户端上注册了错误回调:
this.onlineHub.client.error = (exc: any): void => {
console.log('Error occured:', exc);
};