Reputation: 467
I am building a web application using AngularJS and SignalR. To do this, I based my code off of this blog: http://sravi-kiran.blogspot.com/2013/09/ABetterWayOfUsingAspNetSignalRWithAngularJs.html
I have also been using http://www.asp.net/signalr/overview/signalr-20/hubs-api/hubs-api-guide-javascript-client#logging to verify that my code is formatted correctly. However, my code is not working correctly.
Here's some code:
Startup.cs
public class Startup
{
public void Configuration(IAppBuilder app)
{
app.MapSignalR();
}
}
CarHub.cs
public class CarHub : Hub
{
public void Send(string carType)
{
// Call the broadcastMessage method to update clients.
System.Diagnostics.Debug.WriteLine("Sending! - " + carType);
Clients.All.someoneGotANewCar(carType);
}
}
Angular Service
homeCarspageModule.service('signalRSvc', ["$", "$rootScope", function ($, $rootScope) {
var proxy = null;
var initialize = function ()
{
alert("Initialize!");
//Getting the connection object
var connection = $.hubConnection();
//Creating proxy
proxy = connection.createHubProxy('carHub');
//Starting connection
connection.start();
connection.logging = true;
//Publishing an event when server pushes a new car
proxy.on('someoneGotANewCar', function (carType) {
alert("Emit! - " + carType);
$rootScope.$emit("someoneGotANewCar", carType);
});
alert("Initialization Complete!");
};
var sendRequest = function (carType) {
//Invoking send method defined in hub
alert("Invoking!");
proxy.invoke('send', carType);
};
return {
initialize: initialize,
sendRequest: sendRequest
};
}]);
Angular Controller
var mainCarsController = ["$scope", "$http", "$location", "$routeParams", "dataService", "signalRSvc", "$rootScope",
function($scope, $http, $location, $routeParams, dataService, signalRSvc, $rootScope) {
$scope.person = null;
//Get car data from server
dataService.getPersonByIdIncludeCarsAndOwners($routeParams.personId)
.then(function(result) {
$scope.person = result;
}, function() {
alert("carsController (1) : Error connecting to server");
});
//SignalR
var updateOnNewCar = function (text) {
alert("Updating!");
alert("SignalR received: " + text);
}
$rootScope.$on("someoneGotANewCar", function (e, carType) {
$scope.$apply(function () {
alert("Recieved!");
updateOnNewCar(carType);
});
});
signalRSvc.initialize();
}];
My code will get to the WriteLine in carhub.cs, and I get this from the logger:
So I know someoneGotANewCar() has been invoked. However, I would next expect the alert("Emit") in my service to occur on another browser, yet this does not happen. Can someone help me find out why?
If you need more code to help find the solution just ask and I'll edit it in.
Upvotes: 0
Views: 3187
Reputation: 3425
You have to declare your proxy callback (proxy.on(...)
) before starting the connection (connection.start()
).
Upvotes: 3