简体   繁体   中英

How to connect signalR from angularJs

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.

enter image description here

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 class

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

               }
            }

        }

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

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 code

<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:

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>

Basic Sample:

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>

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

SignalR Angular Module:

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

I can able to connect webapi by adding below code into my Startup.Auth.cs

public void ConfigureAuth(IAppBuilder app)
    {
        app.UseOAuthBearerTokens(OAuthOptions);

        //by adding below code 
        app.UseCors(CorsOptions.AllowAll);
        app.MapSignalR(new HubConfiguration { EnableJSONP = true });

    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM