1

I have an Angular application where certain routes listen for certain SignalR messages and some messages are listened for by multiple routes. Everything is working fine but when I navigate from Route A to Route B, Route A's handler functions for the SignalR events are still being fired. I'm using an Angular service to wrap the SignalR hub and keep track of callback functions. I considered just resetting the array of callback functions on every route change but I get the feeling that's not the right way to do this. Given there should only be one hub connection and route-specific event handling, what's the appropriate way to do this?

Angular SignalR Service

app.factory('SignalRService', [function () {

    var eventCallbacks = [];

    var entityHub = $.connection.entityHub;

    entityHub.client.event = function (payload) {
        angular.forEach(eventCallbacks, function (callback, idx) {
            callback(payload);
        });
    };

    $.connection.hub.start({ transport: 'longPolling' })
        .done(function () {  })
        .fail(function () {  });

    return {
        subscribeToEvent: subscribeToEvent
    };

    function subscribeToEvent(callback) {
        eventCallbacks.push(callback);
    }


}]);
Jeff Swensen
  • 3,513
  • 28
  • 52

2 Answers2

1

Best solution looks like a refactor to use the $rootScope.$on and $emit combination here: https://stackoverflow.com/a/19498009/100776

Community
  • 1
  • 1
Jeff Swensen
  • 3,513
  • 28
  • 52
1

I found a great example using $on and $emit here: http://sravi-kiran.blogspot.com/2013/09/ABetterWayOfUsingAspNetSignalRWithAngularJs.html

Currently trying to find a better way to inject the $.connection or hub proxy dependency....

Jason Capriotti
  • 1,836
  • 2
  • 17
  • 33