【发布时间】:2015-01-12 02:03:36
【问题描述】:
我正在实现功能,以在 AngularJS 应用程序中使用 SignalR 通知用户长时间运行的作业完成。我已经根据他们的姓名创建了用户组,因此对于每个用户,他都有一组他的姓名和他打开的不同连接 ID up 将被创建,并且他的组将通知他。我想在两个页面上通知用户,即登录页面和作业运行页面,即使用户在登录页面并且作业运行完成,他也应该收到通知。
出于同样的原因,我在两个页面上都按他的名字创建了组,这样如果他在任何页面上,他都会通过该组得到通知。
在登录页面控制器 js 文件中,我编写了代码以将用户添加到组中,如下所示...
$rootScope.signalRHub = $.connection.signalRHub;
$rootScope.hubStart = null;
$rootScope.startHub = function () {
if ($rootScope.hubStart == null)
{
$rootScope.hubStart = $.connection.hub.start();
}
return $rootScope.hubStart;
}
$scope.$on('$locationChangeStart', function (event) {
if ($rootScope.userName != "") {
$rootScope.signalRHub.server.leaveGroup($rootScope.userName);
}
});
// Start the connection
$rootScope.startHub().done(function () {
$rootScope.signalRHub.server.joinGroup($rootScope.userName);
});
在 Job Run 控制器 js 文件上,我编写了以下代码....
$rootScope.signalRHub.client.showNotification = function (message) {
notify('Your notification message');//notify is the angular js directive injected in this controller which runs fine
};
$scope.$on('$locationChangeStart', function (event) {
$rootScope.signalRHub.server.leaveGroup($rootScope.studyid);
});
// Start the connection
$rootScope.startHub().done(function () {
$rootScope.signalRHub.server.joinGroup($rootScope.userName
});
我的 Hub 文件.....
[EnableCors(origins: "*", headers: "*", methods: "*")]
public class SignalRHub : Hub
{
public Task JoinGroup(string groupName)
{
return Groups.Add(Context.ConnectionId, groupName);
}
public Task LeaveGroup(string groupName)
{
return Groups.Remove(Context.ConnectionId, groupName);
}
public void ShowNotification(string jobRunDetailId, string userName)
{
if (!string.IsNullOrEmpty(userName))
{
var context = GlobalHost.ConnectionManager.GetHubContext<SignalRHub>();
context.Clients.Group(userName).showNotification(jobRunDetailId);
}
}
}
问题是当我运行应用程序时,两个页面的组添加功能都可以正常工作。但是当我从 Hub 调用“showNotification”时,它没有显示任何消息。
但奇怪的是,如果我在登录页面上评论“$rootScope.startHub().done....”功能,那么作业运行页面通知功能工作正常。我不确定是否写“$rootScope.startHub( ).done()..." 在两个地方造成了这个问题。请帮助。
【问题讨论】:
-
您需要确保的一件事是
$rootScope.signalRHub.client.showNotification在您开始连接之前 被定义。如果这没有发生,那就可以解释为什么没有调用showNotification。 -
@halter73:- 非常感谢...我在连接开始之前更改了代码并在第一页中移动了所有函数声明,它开始工作...如果您在答案部分中写了这个我会接受它...:P
标签: angularjs sockets signalr long-polling connection