AngularJS和SignalR的区别在于定义app模块



我正试图将我的SignalR代码与angular集成。我已经遵循了,也许,5个不同的教程,但不能让它工作。

遵循本教程,我的代码中唯一的区别是我的app.js文件看起来像这样:
var myApp = angular.module('myApp', []);
$(function () {
      $.connection.hub.url = server;
      $.connection.hub.logging = true;
      $.connection.hub.start().done(function () {
          console.log('Hub connection open. ID: ' + $.connection.hub.id);
      });
});
angular.module('myApp').value('chat', $.connection.testhub);

和教程app.js看起来像这样:

(function() {
  angular.module('myApp', [])
  $(function () {
      $.connection.hub.url = server;
      $.connection.hub.logging = true;
      $.connection.hub.start().done(function () {
          console.log('Hub connection open. ID: ' + $.connection.hub.id);
      });
   });
  angular.module('myApp').value('chat', $.connection.testhub);
});

当从控制器访问'chat'服务时,我可以console.log我的hub。但是SignalR日志说连接开始发生在订阅任何集线器之前,所以当然没有调用客户端方法。

所以我的问题是,我们的app.js文件的差异是这个问题的原因吗?,为什么?

其他一切都是相同的,我已经验证了SignalR服务器工作正常

您需要将在done回调触发之前触发的所有请求排队。我已经为SignalR做了一个抽象库,我像这样解决了它

https://github.com/AndersMalmgren/SignalR.EventAggregatorProxy/blob/master/SignalR.EventAggregatorProxy.Client.JS/jquery.signalR.eventAggregator.js L164

我还限制了请求,以便在顺序触发大量请求时可以一起发送

https://github.com/AndersMalmgren/SignalR.EventAggregatorProxy/blob/master/SignalR.EventAggregatorProxy.Client.JS/jquery.signalR.eventAggregator.js L184

你可以看看这个库,它是用MVVM设计的,也应该适合MVChttps://github.com/AndersMalmgren/SignalR.EventAggregatorProxy/wiki

演示项目https://github.com/AndersMalmgren/SignalR.EventAggregatorProxy/tree/master/SignalR.EventAggregatorProxy.Demo.MVC4

现场演示http://malmgrens.org/signalR/

在多次不同的尝试没有成功之后,我决定使用我的ApplicationController(所有控制器的父)作为SignalR处理程序。从那里,我可以订阅所有必要的中心和广播事件到子作用域,以处理不同的需求。我知道这不是最佳实践,但对于我的小应用程序来说,这可能已经足够了。

myApp.controller('ApplicationController', ['$scope', 'logger', 'AuthService', function ($scope, logger, AuthService) {
$.connection.hub.url = serverUrl;
$.connection.hub.logging = true;
$.connection.testhub.client.getStaff = function (value) {
    $scope.$broadcast('someEvent', value);
};
$.connection.hub.start().done(function () {
    console.log('Hub connection open. ID: ' + $.connection.hub.id);
});
$.connection.hub.error(function (err) {
    console.log("Error: " + err);
});
}]);

所以我将广播发送事件下游和发射发送它们从子控制器到父。我想这个可以。

最新更新