我正在使用AngularJS和SignalR构建Web应用程序。为此,我将此代码基于此博客:http://sravi-kiran.blogspot.com/2013/09/ABetterWayOfUsingAspNetSignalRWithAngularJs.html
我一直在使用http://www.asp.net/signalr/overview/signalr-20/hubs-api/hubs-api-guide-javascript-client#logging来验证我的代码是否格式正确。但是,我的代码无法正常工作。
这里有一些代码:
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);
}
}
角色服务
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
};
}]);
角度控制器
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();
}];
我的代码将转到carhub.cs中的WriteLine,我从记录器中获取此代码:
所以我知道有人已经调用了GotANewCar()。但是,我接下来会希望我的服务中的警报(" Emit")在另一个浏览器上发生,但这不会发生。有人可以帮我找出原因吗?
如果您需要更多代码来帮助找到解决方案,请直接询问,然后我将对其进行编辑。
答案 0 :(得分:3)
您必须在开始连接(proxy.on(...)
)之前声明代理回调(connection.start()
)。