I use AngularJS to create a SignalR service that connects to the hub that I specify and provides methods .onand .invokeso that my controllers can listen for events from the server and call methods on the server.
Here is the relevant part of my service:
return {
on: function (eventName, callback) {
hub.on(eventName, function (result) {
$root.$apply(function () {
if (callback) {
callback(result);
}
});
});
},
ready: function (callback) {
return isLoaded.then(function () {
callback();
});
},
invoke: function (methodName, args, callback) {
return hub.invoke.apply(hub, $.merge([methodName], $.makeArray(args))).done(function (result) {
$root.$apply(function () {
if (callback) {
callback(result);
}
});
});
},
connection: connection
};
My hub connects nicely, however, when I try to make a call, nothing happens. Here where I call it:
var chatHub = hub('chatHub');
chatHub.on('userConnected', function (user) {
console.log(user);
});
chatHub.ready(function () {
chatHub.invoke('Connect', [
{ Name: $root.auth.profile.name, Picture: $root.auth.profile.picture },
{ RoomKey: $routeParams.roomKey, RoomID: $routeParams.roomId }
]);
});
, .ready(), , , , . ( isLoaded connection.start(). Done(), , )
.invoke ( console.log), :
public class ChatHub : Hub {
public async void Connect(User user, Room room) {
}
}
, , :
public class Room {
public int RoomKey { get; set; }
public string RoomID { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public List<User> Users { get; set; }
public List<Message> Messages { get; set; }
}
public class User {
public string Name { get; set; }
public string Picture { get; set; }
}
, , , , (, ).
, chatHub.invoke('Connect', ...), , , , ~/signalr/hubs ( , , , )
proxies['chatHub'] = this.createHubProxy('chatHub');
proxies['chatHub'].client = { };
proxies['chatHub'].server = {
connect: function (user, room) {
return proxies['chatHub'].invoke.apply(proxies['chatHub'], $.merge(["Connect"], $.makeArray(arguments)));
}
};