如何从angularJs连接signalR
How to connect signalR from angularJs
我在。net中开发web应用程序,作为两个独立的应用程序,后端使用webapi c#,用户界面使用AngularJS。我只是想在这个项目中添加聊天选项。我已经安装了SignalR,并在webapi中添加了ChatHub.cs类。
输入图片描述
在WebAPI中有一个类叫做Startup.cs
public partial class Startup
{
public void Configuration(IAppBuilder app)
{
HttpConfiguration config = new HttpConfiguration();
config.Formatters.JsonFormatter.SerializerSettings.DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Local;
WebApiConfig.Register(config);
app.UseCors(CorsOptions.AllowAll);
ConfigureAuth(app);
app.UseWebApi(config);
app.MapSignalR();//added after installation of SignalR package
}
}
ChatHub类
public class ChatHub : Hub
{
public static string emailIDLoaded = "";
public void Connect(string userName, string email)
{
emailIDLoaded = email;
var id = Context.ConnectionId;
using (SmartCampEntities dc = new SmartCampEntities())
{
var userdetails = new ChatUserDetail
{
ConnectionId = id,
UserName = userName,
EmailID = email
};
dc.ChatUserDetails.Add(userdetails);
dc.SaveChanges();
}
}
}
无论我从用户界面发送什么请求,它都会在webAPI中命中相应的控制器。例如
$http({
method: 'GET',
url: $scope.appPath + "DashboardNew/staffSummary" //[RoutePrefix]/[Route]
}).success(function (result, status) {
data = result;
});
我的用户界面是一个单独的应用程序。我如何从UI连接信号r。我尝试了一些方法,但没有成功。谁能告诉我如何使它工作?
html代码
<div>
<a class="btn btn-blue" ng-click="sendTask()">SendTask</a>
javascript angular.module('WebUI').controller('DashboardCtrl', function ($scope, $window, $http, $modal, ngTableParams) {
$scope.header = "Chat";
$scope.sendTask = function () {
$http({
method: 'POST',
url: $scope.appPath + hubConnetion.server.sendTask("userName","email"),
})
}
});
Basics:
你可以连接到你的信号服务器,你必须包括客户端代码到你的页面。之前包含jquery也很重要。在使用hubs的情况下,至少还可以包含生成hubs文件:
<script src="Scripts/jquery-1.10.2.min.js"></script>
<script src="Scripts/jquery.signalR-2.1.0.min.js"></script>
<script src="signalr/hubs"></script>
基本示例:
这里有一个完整的示例(不带和带生成的hub代理):
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta charset="utf-8" />
</head>
<body>
<div class="container">
<div class="row">
<!-- Title -->
<h1>SignalR Sample</h1>
</div>
<div class="row">
<!-- Input /Button-->
<input type="text" id="inputMsg" />
<button button="btn btn-default" id="btnSend">Send</button>
</div>
<div class="row">
<!-- Message list-->
<ul id="msgList"></ul>
</div>
</div>
<script src="Scripts/jquery-1.6.4.js"></script>
<script src="Scripts/jquery.signalR-2.2.0.js"></script>
<script src="http://[LOCATIONOF YOUR HUB]/signalr/hubs"></script>
<script>
// ------------------- Generated Proxy ----------------------------
$(function () {
$.connection.hub.url = "[LOCATION WHERE YOUR SERVICE IS RUNNING]/signalr";
var chat = $.connection.myChat;
chat.client.addMessage = function (name, message) {
$('#msgList').append('<li><strong>' + name
+ '</strong>: ' + message + '</li>');
};
$.connection.hub.start({}).done(function () {
$('#btnSend').click(function () {
chat.server.Send("Stephan", $('#inputMsg').val());
$('#inputMsg').val('').focus();
});
})
});
//// ------------------- Without Proxy ----------------------------
//$(function () {
// var connection = $.hubConnection("http://localhost:8080/signalr");
// var chatHubProxy = connection.createHubProxy('chatHub');
// chatHubProxy.on('AddMessage', function (name, message) {
// console.log(name + ' ' + message);
// $('#msgList').append('<li><strong>' + name
// + '</strong>: ' + message + '</li>');
// });
// connection.start().done(function () {
// $('#btnSend').click(function () {
// chatHubProxy.invoke('send', "Stephan", $('#inputMsg').val());
// $('#inputMsg').val('').focus();
// });
// });
//});
</script>
</body>
</html>
详细信息请参见:http://www.asp.net/signalr/overview/guide-to-the-api/hubs-api-guide-javascript-client
SignalR Module:
还有一个"helper模块",你可以在angularjs中使用它来处理signalr:https://github.com/JustMaier/angular-signalr-hub
我可以通过在Startup.Auth.cs中添加下面的代码来连接webapi
public void ConfigureAuth(IAppBuilder app)
{
app.UseOAuthBearerTokens(OAuthOptions);
//by adding below code
app.UseCors(CorsOptions.AllowAll);
app.MapSignalR(new HubConfiguration { EnableJSONP = true });
}
相关文章:
- SignalR客户端启动连接时如何设置用户
- SignalR连接到多个服务器
- SignalR异常“;无法识别的用户标识.在活动SignalR连接期间,用户标识无法更改&”;
- 尝试在 Chrome 扩展程序中使用 SignalR 连接到中心时出错
- SignalR 客户端不知道连接失败
- SignalR:在调用方法之前等待重新建立连接
- Signalr:JavaScript 客户端无法在 IE 上重新连接(解析错误异常)
- SignalR-处理来自JavaScript客户端的多个集线器连接
- SignalR维护不同子页面之间的连接ID
- Signalr-连接已启动,但未使用websocket调用客户端事件
- SignalR在哪个阶段自动重新连接
- 连接开始后连接到SignalR集线器
- 是否可以在SignalR中为每个客户端创建不同的连接?持久连接
- SignalR IUserIdProvider未为用户ID和连接ID映射调用
- 无法从javascript客户端连接signalR集线器
- SignalR连接被阻止,直到加载页面图像
- SignalR客户端应用程序在VS2008中运行时无法连接
- SignalR调用方法:必须先启动连接,然后才能发送数据
- 如何获得SignalR集线器连接以跨域工作
- 如何从angularJs连接signalR