gpt4 book ai didi

javascript - 未收到 SignalR 客户端方法调用

转载 作者:行者123 更新时间:2023-11-28 19:46:46 24 4
gpt4 key购买 nike

我正在使用 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);
}
}

Angular 服务

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();

}];

我的代码将到达 carhub.cs 中的 WriteLine,我从记录器中获取此信息:enter image description here

所以我知道 有人GotANewCar() 已被调用。但是,接下来我希望我的服务中的警报(“Emit”)发生在另一个浏览器上,但这并没有发生。有人可以帮我找出原因吗?

如果您需要更多代码来帮助找到解决方案,请询问,我将对其进行编辑。

最佳答案

在启动连接 (connection.start()) 之前,您必须声明代理回调 (proxy.on(...))。

关于javascript - 未收到 SignalR 客户端方法调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24147507/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com