How to dynamically add hub to SignalR and have different scopes

馋奶兔 提交于 2019-12-03 17:09:32

I think I have a more elegant solution.

Service

 app.factory("signalrFactory", function ($rootScope, $http, $timeout) {
    var factory = {};
    factory.connection = $.connection;

    var startDoneFunctions = [];
    var debounce;

    factory.start = function (done) {
        factory.connection.hub.stop();

        if (done) {
            if (startDoneFunctions.indexOf(done) == -1) {
                startDoneFunctions.push(done);
            }
        }
        if (debounce) $timeout.cancel(debounce);
        debounce = $timeout(function () {
            factory.connection.hub.start().done(function () {
                for (var x = 0; x < startDoneFunctions.length; x++) {
                    startDoneFunctions[x]();
                }
            });
        }, 100);
    };

    return factory;
});

Use

controller('customerSummary', function ($scope, signalrFactory) {
        $scope.customerHub = signalrFactory.connection.customerHub;
        $scope.customer;
        $scope.beingEditedText = "";



        $scope.customerHub.client.beingEdited = function (text) {
            $scope.beingEditedText = text;
        };
        $scope.customerHub.client.doneEditing = function () {
            $scope.beingEditedText = "";
        };

        $scope.customerHub.client.updateCustomer = function (customer) {
            $scope.customer = customer;
            $scope.$apply();
        };

        $scope.init = function (id) {
            signalrFactory.start(function () {
                $scope.customerHub.server.getCustomer(id);

            });
        };
    });

What this way allows is to add when needed and not having to add each hub at bootstrap. I am now able to have different done() methods from anywhere.

Rohan Büchner

Note

While the solution below worked for me at first. I opted to use the solution provided above, which worked quite well in the end.


Original answer

My initial understanding of signalR was slightly flawed. I ended up creating a provider for this as well so i can configure it upfront.

Config

app.config(['signalrSvcProvider', function (signalrSvcProvider) {
    signalrSvcProvider.start(['global','dashboard']);
}]);

Provider

(function () {
    'use strict';

    angular.module('app').provider('signalrSvc', signalrSvc);

    function signalrSvc() {

        var self = this;

        self.hubs = [];

        this.start = function (hubs) {

            var connection = $.hubConnection("someurl/signalr");

            // convert hubNames to actual hub proxies, and append default client communication functions
            $.each(hubs, function (idx, hub) {
                var proxy = connection.createHubProxy(hub);

                // a minimum of one client function needs to be registered to be able to complete the connection
                proxy.on('pingBack', function (data) { console.log(hub.hubName + ", connected: " + data); });
                proxy.on('receiveError', function (data) { console.log(hub.hubName + ", error: " + data); });

                self.hubs[idx] = proxy;
            });

            // add security token before attmpting connect
            $.ajaxPrefilter(function (options) {
                if (!options.beforeSend) {
                    options.beforeSend = function (xhr) {
                        var token = $.cookie(".cttid").replace(/"/g,'');
                        xhr.setRequestHeader('Authorization', 'Bearer ' + token);
                    };
                }
            });

            // connects and run initialise for each hub
            connection.start({ transport: 'longPolling' })
                .done(function () {
                    $.each(self.hubs, function (idx, hub) {
                        hub.invoke('initialise');
                    });
                });
        };

        this.$get = ['filterFilter', function (filterFilter) {
            return {
                hub: function (name) {
                    return filterFilter(self.hubs, { hubName: name }, true)[0];
                }
            };
        }];
    }

})();

Usage

var hub = signalrSvc.hub('dashboard');

hub.on('getAllUnapprovedAgreements', function (data) {
      //do something
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!