Improve this AngularJS factory to use with socket.io

后端 未结 13 1472
你的背包
你的背包 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:58

    I use something like the code below. socketsService is only instantiated once and I believe Angular takes care of GC the $on's

    If you don't like $broadcast/$on, there are some slightly more solid Message Bus implementations for Angular available...

    app.service('socketsService', ['$rootScope', function ($rootScope) {
        var socket = window.io.connect();
    
        socket.on('info', function(data) {
            $rootScope.$broadcast("info_received", data);
        });
    
        socket.emit('ready', "Hello");
    }]);
    
    app.controller("infoController",['$scope',
        function ($scope) {
            $scope.$root.$on("info_received", function(e,data){
                console.log(data);
            });
            //...
        }]);
    
    app.run(
        ['socketsService',
            function (socketsService) {
            //...
        }]);
    

提交回复
热议问题