1

I've setup an AngularJS app using websockets and it seems to be working. Here is a summary of whats going on:

var app = angular.module('websocketApp',[]);

app.factory('WebSocket',function($rootScope) {
    var websocket = new WebSocket(websocket_url);
    var items = [];

    websocket.onmessage = function(msg) {
        items.push(JSON.parse(msg.data));
        $rootScope.$broadcast('new_message');    
    }

    return {
        fetchItems: function() {
            return items;
        }
    }
});

app.controller('ItemsCtrl',function($scope,WebSocket) {
    $scope.$on('new_message',function() {
        $scope.$apply(function() {
            $scope.items = WebSocket.fetchItems();
        });
    });
});

My question is if anyone else has setup an Angular app using websockets and if this implementation is the correct way to go about it or if there is a better solution. I've read many cons on using $broadcast but this seems to be the correct usage of the $broadcast functionality.

1 Answer 1

1

The way you have done it seems fine. An alternative way I do it though is to store an event/callback array, and register the events on it that I want to receive specifically.

For example:

angular.module('myapp.services.socket', [])
    .factory('io', ['$rootScope', 'globals', function ($rootScope, globals) {

        var socket;
        var curChannel;
        var eventCache = [];

        function isConnected() {
            return socket && socket.socket.connected;
        }

        function on(eventName, callback) {
            socket.on(eventName, function () {  
                var args = arguments;
                $rootScope.$apply(function () {
                    callback.apply(socket, args);
                });
            });
        }

        function emit(eventName, data, callback) {
            socket.emit(eventName, data, function () {                      
                var args = arguments;
                $rootScope.$apply(function () {
                    if (callback) {
                        callback.apply(socket, args);
                    }
                });
            });
        }

        return {
            registerEvent: function(eventName, callback) {
                eventCache.push({ name: eventName, cb: callback });
                if(isConnected()){
                    on(eventName, callback);
                }
            },  
            emit: function (eventName, data, callback) {                
                // firstly check that the socket is connected
                if(isConnected()){
                    emit(eventName, data, callback);
                }else{                  
                    // connect to the server and subscribe upon connection
                    socket = io.connect(globals.api + ':80');

                    socket.on('connect', function(){
                        emit(eventName, data, callback);

                        // add the events from the cache
                        for(var i in eventCache){
                            on(eventCache[i].name, eventCache[i].cb);
                        }
                    });
                }               
            }
        };
    }]);

This way, you can simply register event callbacks whenever you want, by injecting this service, and running:

io.registerEvent('some_event', function(){ /* some logic */ });

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.