Improve this AngularJS factory to use with socket.io

后端 未结 13 1532
你的背包
你的背包 2020-12-07 08:42

I want to use socket.io in AngularJS. I found the following factory:

app.factory(\'socket\', function ($rootScope) {
    var socket = io.connect();
    retur         


        
13条回答
  •  难免孤独
    2020-12-07 09:11

    I just solved a similar problem before I read this. I did it all in the Service.

    .controller('AlertCtrl', ["$scope", "$rootScope", "Socket", function($scope, $rootScope, Socket) {
        $scope.Socket = Socket;
    }])
    
    // this is where the alerts are received and passed to the controller then to the view
    .factory('Socket', ["$rootScope", function($rootScope) {
        var Socket = {
            alerts: [],
            url: location.protocol+'//'+location.hostname+(location.port ? ':'+location.port: ''),
            // io is coming from socket.io.js which is coming from Node.js
            socket: io.connect(this.url)
        };
        // set up the listener once
        // having this in the controller was creating a
        // new listener every time the contoller ran/view loaded
        // has to run after Socket is created since it refers to itself
        (function() {
            Socket.socket.on('get msg', function(data) {
                if (data.alert) {
                    Socket.alerts.push(data.alert);
                    $rootScope.$digest();
                }
            });
        }());
        return Socket;
    }])
    

提交回复
热议问题