【发布时间】:2018-10-10 12:42:36
【问题描述】:
我能够连接到我的集线器并且我已经连接了 OnConnected 和 OnDisconnected。他们应该从一个整数中加/减,并使用新值调用客户端回调。 我的 Angular 应用程序成功连接到服务器,但我注册的回调函数没有被触发。
这是我的服务器集线器:
[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 方法。
【问题讨论】:
-
哪个方法没有被命中?服务器端 OnConnected()、客户端 listUpdated() 处理程序,还是两者都有?
-
@Learning2Code 两者都有,但错误可能在服务器端 OnConnected() 因为该方法又在客户端调用 listUpdated()。
标签: javascript asp.net angular signalr