Reputation: 1161
I am still learning SignalR. In asp.net web Api I have created a simple hub. And in angular I have created a factory for instantiating connection with the hub.
public class NotificationHub : Hub
{
public void Hello()
{
var x = "test";
Clients.All.hello(x);
}
}
Client side.
.factory("NotificationHub", function(){
var NotificationHubFactory = {};
NotificationHubFactory.proxy = null;
var initialize = function(){
$.connection.hub.url = "http://localhost:18678/signalr";
$.connection.hub.start().done(function(response){
NotificationHubFactory.proxy = $.connection.notificationHub;
}).fail(function(error){
console.log(error);
});
};
initialize();
return NotificationHubFactory;
});
The problem is when I try to do this.
NotificationHub.proxy.server.hello();
NotificationHub.proxy.client.hello = function(data){
console.log(data);
};
NotificationHub.proxy.client.hello
never gets invoked. Although if I put a break point in the hub Clients.All.hello(x);
it fires which means it can not find hello
method in the client.
Any ideas what the problem is?
Upvotes: 1
Views: 6780
Reputation: 37520
You need to attach at least one event handler to the hub before hub.start()
is called. Without that, the client is never registered with the hub. See this note from the documentation here...
Normally you register event handlers before calling the start method to establish the connection. If you want to register some event handlers after establishing the connection, you can do that, but you must register at least one of your event handler(s) before calling the start method. One reason for this is that there can be many Hubs in an application, but you wouldn't want to trigger the OnConnected event on every Hub if you are only going to use to one of them. When the connection is established, the presence of a client method on a Hub's proxy is what tells SignalR to trigger the OnConnected event. If you don't register any event handlers before calling the start method, you will be able to invoke methods on the Hub, but the Hub's OnConnected method won't be called and no client methods will be invoked from the server.
Try this...
.factory("NotificationHub", function(){
var NotificationHubFactory = {};
NotificationHubFactory.proxy = null;
var initialize = function(){
$.connection.hub.url = "http://localhost:18678/signalr";
$.connection.notificationHub.client.hello = function () {};
$.connection.hub.start().done(function(response){
NotificationHubFactory.proxy = $.connection.notificationHub;
}).fail(function(error){
console.log(error);
});
};
initialize();
return NotificationHubFactory;
});
Then replace the hello
handler before calling the server...
NotificationHub.proxy.client.hello = function(data){
console.log(data);
};
NotificationHub.proxy.server.hello();
There's also a potential issue with this code as hub.start()
is asynchronous and the calls can happen before the hub is ready.
Upvotes: 3