如何将Signalr 2与Angular 1.4和Web API 2集成

时间:2017-05-02 10:20:27

标签: javascript html angularjs signalr signalr-hub

我在HTML的底层中包含了引用

<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script src="~/Scripts/jquery.signalR-2.1.2.min.js"></script>
<script src="signalr/hubs"></script>

I add  angular js file here:

<script src="~/ScriptsNg/Controller/TransacCltr.js"></script>
<script src="~/ScriptsNg/Services/CrudService.js"></script>

<div ng-app="myapp">
    <div class="row" ng-controller="TransacCtrl">
       <div class="modal-footer">
          <button type="button" class="btn btn-success" data-dismiss="modal" ng-click="SaveUpdate()">Save</button>
          <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
      </div>
    </div>
</div>

在我的TransacCltr.js文件中,我编写了这段代码:

app.controller('TransacCtrl', ['$scope', 'CrudService', 'Notification',
    function ($scope, CrudService, Notification) {

    $scope.transac = {};
    $scope.btnText = "Save";      
    //method
    $scope.SaveUpdate = SaveUpdate;
    $scope.GetServiceTypeList = GetServiceTypeList;
    $scope.StatusOk = StatusOk;  
    init();
    function init()
    {
        initilize();
    }
    function initilize()
    {
        Connect();          
    }
    var SignalrConnection;
    function Connect() {
        SignalrConnection = $.connection.myHub;         
        //connecting the client to the signalr hub
        $.connection.hub.start().done(function () {
            alert("Connected to Signalr Server");
        }).fail(function () {
            alert("failed in connecting to the signalr server");
        })
    }
    function SaveUpdate() { 
        var Temperature = parseInt($scope.transac.TrancAmount);
        //calling the ChangeWeather function on the signalr server   
        SignalrConnection.server.change_weather(Temperature)

            }
        }

    }

}]);

$ connection.myHub。这显示我undefined。为什么显示这个? 如果它是未定义的将如何定义。如果我使用它正常的jquery函数它不显示此消息。但如果我在angularjs中使用它然后显示错误消息。如何我可以解决此错误?任何帮助是非常欣赏。

My Hub Class,如下所示:

public class MyHub : Hub
{  
    static int Temperature;
    [HubMethodName("change_weather")]
    public void ChangeWeather(int temperature)
    {
        //change the temperature   
        Temperature = temperature;  
        Clients.Others.NotifyUser(temperature);
    }
    [HubMethodName("get_weather")]
    public void GetWeather()
    {
        //pushing the data only to the user which has called this method.   
        Clients.Caller.NotifyUser(Temperature);
    }  
}

0 个答案:

没有答案