I'm trying to integrate SignalR into my Angular MVC application. I started with this article which provides a hub proxy factory to facilitate hub calls between the server and Angular code. Despite setting everything up, the communication between my server hub and Angular code is not functioning properly. Here's the code snippet:
Hub proxy factory:
app.factory('hubProxy', ['$rootScope', 'signalRUrl', function ($rootScope, signalRUrl) {
function hubFactory(hubName) {
var connection = $.hubConnection(signalRUrl);
var proxy = connection.createHubProxy(hubName);
connection.start().done(function () { });
return {
on: function (eventName, callback) {
proxy.on(eventName, function (result) {
$rootScope.$apply(function () {
if (callback) {
callback(result);
}
});
});
},
invoke: function (methodName, callback) {
proxy.invoke(methodName)
.done(function (result) {
$rootScope.$apply(function () {
if (callback) {
callback(result);
}
});
});
},
connection: connection
};
};
return hubFactory;
}]);
Angular controller:
angular.module('testApp').controller('testController', ['$scope', 'hubProxy', function ($scope, hubProxy) {
var pendingPaymentsHub = hubProxy('pendingPaymentsHub');
pendingPaymentsHub.on('onUpdatePendingPayment', function (data) {
console.log('hub callback!');
});
}]);
Hub:
[HubName("pendingPaymentsHub")]
public class PendingPaymentsHub : Hub
{
private static IHubContext hub = GlobalHost.ConnectionManager.GetHubContext<PendingPaymentsHub>();
public static void UpdatePendingPayment(PendingPaymentViewModel pendingPayment)
{
hub.Clients.All.onUpdatePendingPayment(pendingPayment);
}
}
The hub is called from an API controller post-update. It is triggered like this:
PendingPaymentsHub.UpdatePendingPayment(pendingPayment);
Upon page load, both /signalr/negotiate
and /signalr/start
requests run successfully (200 status confirmed in browser dev tools). In addition, I've verified that the UpdatePendingPayment
method in the hub is being executed during debugging. However, there is no activity happening on the front-end. What could be causing this?
Thank you for your assistance.
Update: The issue lies within the hub proxy factory implementation. If I replace it with the following code snippet in my controller, everything works as intended:
function initializeHub() {
connection = $.hubConnection(signalRUrl);
hub = connection.createHubProxy('pendingPaymentsHub');
hub.on('onUpdatePendingPayment', function (data) {
console.log('success');
});
connection.start();
};