简体   繁体   中英

AngularJS + WebSockets

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:

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

PS 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)

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

Please take a look at this answer : 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.

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