【发布时间】:2014-06-11 03:43:35
【问题描述】:
我正在使用 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() 已被调用。但是,接下来我希望我的服务中的 alert("Emit") 发生在另一个浏览器上,但这不会发生。有人可以帮我找出原因吗?
如果您需要更多代码来帮助找到解决方案,请询问,我会进行编辑。
【问题讨论】:
标签: javascript angularjs signalr signalr-hub