如何连接angularJs的signalR [英] How to connect signalR from angularJs

查看:70
本文介绍了如何连接angularJs的signalR的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在.NET中将Web应用程序开发为两个独立的应用程序,后端使用webapi c#,而用户界面使用AngularJS.我只想在此项目中添加聊天选项.我已经安装了SignalR并在webapi中添加了ChatHub.cs类.

I am developing web application in .NET as two separate applications, back end using webapi c# and user interface using AngularJS. I just want to add Chat option in this project. I have installed SignalR and added ChatHub.cs class in webapi.

在此处输入图像描述

在WebAPI中,有一个名为Startup.cs的类.

in WebAPI there is a class named 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中的相应控制器.例如

Whatever request i send from user interface it will hit to its corresponding controller in webAPI. For example

 $http({
    method: 'GET',
    url: $scope.appPath + "DashboardNew/staffSummary"  //[RoutePrefix]/[Route]
}).success(function (result, status) {
    data = result;
});

我的用户界面是一个单独的应用程序.如何从UI连接signalR. 我尝试了一些东西,但没有成功.谁能建议我如何使它工作

My user interface is a separate application. How can i connect signalR from UI. I tried something but didn't get it work. Can anyone suggest me how to get it work

html代码

<div>    
<a class="btn btn-blue"  ng-click="sendTask()">SendTask</a>

javascript

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"),
    })   
}

});

推荐答案

基础知识:

要连接到信号发送器服务器,必须在页面中包含客户端代码.在之前包含jquery也很重要. 在使用集线器的情况下,至少还可以包括generate hubs文件:

That you can connect to your signalr server you have to include the client code to your page. It's also important that you include jquery before. At least you can also include the generate hubs file in the case you are working with 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>

基本示例:

这里有一个完整的示例(不带生成的集线器代理):

Here you have a full sample (without and with generated hub proxy):

<!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>:&nbsp;&nbsp;' + 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>:&nbsp;&nbsp;' + 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

For more details see: http://www.asp.net/signalr/overview/guide-to-the-api/hubs-api-guide-javascript-client

SignalR Angular模块:

还有一个帮助程序模块",您可以在angularjs中使用它来处理signalr: https://github.com/JustMaier/angular-signalr-hub

There is also a "helper module" which you can use in angularjs for working with signalr: https://github.com/JustMaier/angular-signalr-hub

这篇关于如何连接angularJs的signalR的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆