我有一个Angular应用程序,它有一个包含SignalR交互的服务。我可以从页面和Angular服务中向服务器发送数据,但只能处理页面中的事件(服务中的事件永远不会触发)。
对于某些情况,这是一个测试应用,用于将视频控件放在与正在播放的视频不同的窗口中。
SignalR Hub代码
public class VideoHub : Hub
{
public void SetPlaybackStatus(string status)
{
Clients.All.statusChanged(status);
}
}
角度控制器
commsTest.controller("videoController", [
'$scope', 'signalRService',
function ($scope, signalRService) {
$scope.playbackStatus = "No Status";
signalRService.onStatusChanged(function (status) {
console.log("Callback status", status);
$scope.playbackStatus = status;
});
}
]);
SignalR Angular Service
commsTest.service('signalRService', [
'$', function ($) {
var proxy,
initialized = false,
statusChangeCallbacks = [];
var initialize = function (callback) {
// Get the connection object
var connection = $.hubConnection();
// Create proxy
proxy = connection.createHubProxy('videoHub');
// Start connection
connection.start().done(function () {
initialized = true;
console.log("Connected");
callback();
});
// This bit here never fires
proxy.on('statusChanged', function (status) {
console.log("Caught from service.", status);
callStatusChangedCallbacks(status);
});
};
var setPlaybackStatus = function (status) {
if (!initialized) {
initialize(function() {
setPlaybackStatus(status);
});
} else {
// This bit works as expected
proxy.invoke('setPlaybackStatus', status);
}
};
var onStatusChanged = function (callback) {
if (callback) {
statusChangeCallbacks.push(callback);
}
};
function callStatusChangedCallbacks(status) {
for (var i = statusChangeCallbacks.length - 1; i >= 0; i--) {
statusChangeCallbacks[i](status);
}
}
return {
onStatusChanged: onStatusChanged,
setPlaybackStatus: setPlaybackStatus
};
}
]);
事件处理程序(上面标记)从不在服务中触发。我直接在页面上有这段代码:
$(function() {
// Gett the connection object
var connection = $.hubConnection();
// Create proxy
var proxy = connection.createHubProxy('videoHub');
// Start connection
connection.start();
// This gets called as expected
proxy.on('statusChanged', function (status) {
console.log("Caught in page.", status);
});
})
当服务器代码发出更新时,会按预期触发。
我也尝试在JS端使用直接方法而不是代理,但我得到了相同的结果。
即
var videoHub = $.connection.videoHub;
videoHub.client.statusChanged = function (status) {
console.log("Callback within service");
callStatusChangedCallbacks(status);
};
在Angular中封装对象是否会阻止JS在拾取事件时停止播放?
为了完成起见,我正在传递jQuery:
var commsTest = angular.module('commsTest', ['ngRoute'])
.config(['$locationProvider', '$routeProvider', '$httpProvider', function ($locationProvider, $routeProvider, $httpProvider) {
delete $httpProvider.defaults.headers.common['X-Requested-With'];
// Routes stuff
}]);
commsTest.value('$', $);
非常欢迎任何建议。