AngularJS与signalR服务无法在服务器调用上工作

时间:2016-11-28 08:24:23

标签: angularjs signalr angular-services signalr.client

我正在尝试在我的应用中创建聊天服务。这是我的signalR角度服务代码。我想要做的是不重复我的代码,我想继续创建另一个功能,如在第一个非工作情况下,但我没有弄清楚如何完成它。有人可以告诉我问题在哪里或者这两种类型的回报之间有什么区别。在这两种情况下,它都是初始化的,但仅在第二种情况下它从服务器端捕获调用。我没有包含Hub,因为没有任何与此问题相关的内容

(function () {
app.service("SignalRService", ["$rootScope", SignalRService]);
"use strict";
function SignalRService($rootScope) {
    //this is not working version
    return {
        channelHub: null,
        initialize: function () {
            //var chatHub = $.connection.channelHub;
            var connection = $.hubConnection();
            this.channelHub = connection.createHubProxy('channelHub');
            // Start Hub
            connection.start().done(function () { });
        },
        getMsg: function (eventName, callback) {
            this.channelHub.on(eventName, function () {
                var args = arguments;
                $rootScope.$apply(function () {
                    callback.apply(this.channelHub, args);
                })
            })
            console.log(eventName);
        }
    }
    //but if i retype it like this its working w/o any problem
    return {      
        getMsg: function (eventName, callback) {
            var connection = $.hubConnection();
            var channelHub = connection.createHubProxy('channelHub');

            channelHub.on(eventName, function () {
                var args = arguments;
                $rootScope.$apply(function () {
                    callback.apply(channelHub, args);
                });
            });
            connection.start().done(function () { });
        }
    };
}})();

这是我的角度控制器,我调用servis初始化函数,根据debuger和控制台日志,函数“newChannelMessage初始化并且没有抛出错误

(function () {
app.controller("ChannelController", ["$scope", "$http", "SignalRService" ]);
function ChannelController($scope, $http, SignalRService) {
    "use strict";
    //**--------------------signalR--------------------------------**//
    SignalRService.initialize();
    SignalRService.getMsg("newChannelMessage", function (message, username) {
        $scope.channel.push(message, username);
    });
}})();

这是我的服务器控制器,我在其中调用“newChannelMessage”函数,但它在客户端从未到达此函数,并且在我实现的方法的第一种情况下没有发生任何事情

    public class CommentController : BaseApiController
{
    private ApplicationDbContext _context;
    private CommentRepository _repository;
    private IHubContext _ctx;

    public CommentController()
    {
        //initialize of db context
        _context = new ApplicationDbContext();
        _repository = new CommentRepository();
        _ctx = GlobalHost.ConnectionManager.GetHubContext<ChannelHub>();
    }

    [Route("create")]
    [HttpPost]
    public async Task SendMsg([FromBody] JObject data)
    {
        var channelId = data["idData"].ToObject<int>();
        Comment comment = data["channelMsgData"].ToObject<Comment>();
        comment.UserId = await GetIdUsingUsername(comment.UserName);         
        await _repository.StoreChannelMessage(comment, channelId);
        _ctx.Clients.All.newChannelMessage(comment.Message, comment.UserName);
    }

    public async Task<string> GetIdUsingUsername(string username)
    {
        var user = await _context.Users.FirstOrDefaultAsync(x => x.UserName == username);
        var id = user.Id;
        return id;
    }
}

1 个答案:

答案 0 :(得分:0)

请试试这个

function SignalRService($rootScope) {

            var connection = null;
            var channelHub = null;

            var initialize = function () {
                connection = $.hubConnection();
                channelHub = connection.createHubProxy('channelHub');
                connection.start().done(function () {
                    console.log("Hub started");
                });
            }

            var getMsg = function (eventName, callback) {
                var deferred = $q.defer();
                channelHub.on(eventName, function () {
                    var args = arguments;
                    $rootScope.$apply(function () {
                        callback.apply(channelHub , args);
                    });
                });
            }


            return {
                initialize: initialize,
                getAllUsers: getAllUsers
            }
}