SignalR: How to add a client call after starting the hub?

Firstly, I just started trying to add SignalR 2 to my existing Angular SPA project.

I have a main controller that immediately starts a hub, which sends some messages to the client. Inside, I have several sub pages, and each one can subscribe to another center for services. The problems are that the client does not receive the message because it is connected after the hub is already running in the main controller.

As a test, if I comment on the start of the hub in the main controller, the one that is on the secondary controller works fine.

From what I read, by design, you need to connect all client calls before starting the hub. I don’t understand ... if this is a service, I should be able to subscribe or unsubscribe at any time after starting the hub. Why not? How to manage?

+6
source share
1 answer

Since there was no answer for 12 hours (which is rather unusual), I had to dig myself. I think that I was misled by the answers from SO on related issues, that you should subscribe to all client calls before starting a connection, as mentioned, for example. here . I found in the Hubs API Guide , one section says

Define a method on the client (without generated proxy or when added after invoking the start method)

Thus, after connecting, you can add a client method. The trick is to use the so-called “no generated proxy”. This limitation applies to "generated proxies."

Below is my working example, taken from the SignalR tutorial.

This is the main controller using "with generated proxies":

$.connection.statusHub.client.updateStatus = function (status) { $scope.status = status; $scope.$apply(); } $.connection.hub.start(); 

This is in a subcontroller using "no generated proxy":

 var connection = $.hubConnection(); var proxy = connection.createHubProxy('stockTickerHub'); proxy.on('updateStockPrice', function (stock) { var st = $scope.stocks.firstOfKey(stock.symbol, 'symbol'); st.lastPrice = stock.lastPrice; $scope.$apply(); }); var hub = $.connection.stockTickerHub; connection.start().done(function () { hub.server.getAllStocks().done(function (stocks) { $scope.stocks = stocks; }); }); 

Note that this does not work if I use "with generated proxies" in the subcontroller as follows:

 var hub = $.connection.stockTickerHub; hub.client.updateStockPrice = function (stock) { var st = $scope.stocks.firstOfKey(stock.symbol, 'symbol'); st.lastPrice = stock.lastPrice; $scope.$apply(); }; $.connection.hub.start().done(function () { hub.server.getAllStocks().done(function (stocks) { $scope.stocks = stocks; }); }); 

To prove the “proxy generated” mode restriction, this code works if I comment on it in the main controller.

By the way, I was so confused by the term with or without a generated proxy in the Guide, and in both cases it is still called xxxProxy. Can't they find a better name? Or does anyone have an explanation?

+8
source

Source: https://habr.com/ru/post/975568/


All Articles