javascript AngularJS + WebSockets

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28556421/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 09:10:48  来源:igfitidea点击:

AngularJS + WebSockets

javascriptangularjswebsocket

提问by Anton Vahmin

I have several controllers. In one of them, i need to open web socket connection. In another i need to listen messages and if needed update $scope. Please help me do that on example below:

我有几个控制器。其中之一,我需要打开网络套接字连接。在另一个我需要收听消息,如果需要更新 $scope。请帮我在下面的例子中做到这一点:

app.controller('MainCtrl', ['$scope', function($scope) {
    $scope.testProp = {};
    $scope.testProp2 = '';
    // listen messages here
    // and update $scope.testProp && $scope.testProp2
}]);

app.controller('SearchCtrl', ['$scope', function($scope) {
    // open connection here
}]);

P.S. i understand that the problem is trivial, but i am new in AngularJS and WebSockets, i need help, and now i don't have time for learn docs (what will i do later)

PS 我知道这个问题很简单,但我是 AngularJS 和 WebSockets 的新手,我需要帮助,现在我没有时间学习文档(我稍后会做什么)

回答by Anton Vahmin

I found a simple solution with factories:

我找到了一个简单的工厂解决方案:

app.factory('socket', [function() {
    var stack = [];
    var onmessageDefer;
    var socket = {
        ws: new WebSocket(websocket_url),
        send: function(data) {
            data = JSON.stringify(data);
            if (socket.ws.readyState == 1) {
                socket.ws.send(data);
            } else {
                stack.push(data);
            }
        },
        onmessage: function(callback) {
            if (socket.ws.readyState == 1) {
                socket.ws.onmessage = callback;
            } else {
                onmessageDefer = callback;
            }
        }
    };
    socket.ws.onopen = function(event) {
        for (i in stack) {
            socket.ws.send(stack[i]);
        }
        stack = [];
        if (onmessageDefer) {
            socket.ws.onmessage = onmessageDefer;
            onmessageDefer = null;
        }
    };
    return socket;
}]);

when

什么时候

app.controller('MainCtrl', ['$scope', 'socket', function($scope, socket) {
    socket.onmessage(function(event) {
        //var data = JSON.parse(event.data);
        //$scope.testVar = 
    });
}]);

app.controller('SearchCtrl', ['$scope', 'socket', function($scope, socket) {
    socket.send({
        //somedata
    });
}]);

回答by vtortola

Please take a look at this answer : AngularJS and WebSockets beyond

请看一下这个答案:AngularJS and WebSockets Beyond

Basically it is an example about creating a WebSocket service in AngularJS that can be used to request/response and publish/subscribe.

基本上它是一个关于在 AngularJS 中创建 WebSocket 服务的示例,该服务可用于请求/响应和发布/订阅。