May 29, 2015

Better AngularJs service for SignalR


SignalR makes our lives easy when buidling realtime webapps. Needless to say AngularJs has already found a permanant role in our webapps. Here is a quick AngularJs service which I wrote to integrate SignalR broadcasts.


 var app = angular.module('signalr', []);  
 app.factory('SignalRService', ['$rootScope', '$window', function ($rootScope, $window) {  
   var srv = {};  
   srv.init = function (hub) {  
     var connection = $.hubConnection();  
     var proxy = connection.createHubProxy(hub);  
     proxy.on('broadcast', function (jobs) {  
       angular.forEach(jobs, function (item) {  
         console.log(item.EventName, item.Data);  
         $rootScope.$broadcast(item.EventName, item.Data);  
       });  
     });  
     connection.start()  
      .done(function () {  
        console.log('Connected');  
      })  
      .fail(function () { console.log('Failed to connect!'); });  
   };  
   return srv;  
 }]);  

No comments: