Improve this AngularJS factory to use with socket.io

后端 未结 13 1526
你的背包
你的背包 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 08:59

    I was having the exact same problem of duplicate events after a browser refresh. I was using a 'factory', but switched to use a 'service'. Here's my socket.io wrapper:

    myApp.service('mysocketio',['$rootScope', function($rootScope)
    {
        var socket = io.connect();
    
        return {
    
            on: function(eventName, callback )
            {
                socket.on(eventName, function()
                {
                    var args=arguments;
                    $rootScope.$apply(function()
                    {
                        callback.apply(socket,args);
                    });
                });
            },
    
            emit: function(eventName,data,callback)
            {
                socket.emit(eventName,data,function()
                {
                    var args=arguments;
                    $rootScope.$apply(function()
                    {
                        if(callback)
                        {
                            callback.apply(socket,args);
                        }
                    });
                });
            }
        }
    
    }]);
    

    I use this service inside my controller and listen for events:

    myApp.controller('myController', ['mysocketio', function(mysocketio)
    {
        mysocketio.on( 'myevent', function(msg)
        {
            console.log('received event: ' + msg );
        }
    }]);
    

    Once I switched from using a factory to using a service, I don't receive duplicates after a browser refresh.

提交回复
热议问题