socket.io angular error:未捕获的TypeError:无法调用null的方法'onClose'

时间:2013-12-06 11:19:20

标签: node.js angularjs socket.io

我正在尝试按照指南进行操作:

http://www.html5rocks.com/en/tutorials/frameworks/angular-websockets/

我正在使用带有angularjs的node,express和socket.io。

当我加载http://localhost:8000/donate时,我在客户端收到了关注错误:

Uncaught TypeError: Cannot call method 'onClose' of null [VM] socket.io.min.js (2806):2
(anonymous function)

相同的角度工厂模式:

app.factory('socket', [
'$rootScope'
    , '$log'
    , function (
        $rootScope
        , $log
        ) {

        var socket = io.connect();

        $log.log('socket', io, socket);

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

节点app.js

var express = require('express')
    , app = express()
    , server = require('http').createServer(app)
    , socket = require('./routes/socket.js')
    , io = require('socket.io').listen(server);

...

//sockets
io.sockets.on('connection', socket.version);

和./routes/socket.js

var socket = module.exports = {}
    , c = console;

socket.version = function(sock){
    var pkg = require('../package.json');

    var version = pkg.version;

    c.log('socket', sock, version);

    sock.emit('send:version', {
        version: version
    });

    setInterval(function () {
        sock.emit('send:time', {
            time: (new Date()).toString()
        });
    }, 1000);
};

最后我在角度控制器中使用它:

app.controller('DonateCtrl', [
    '$scope'
    , '$rootScope'
    , 'socket'
    , '$log'
    , function(
        $scope
        , $rootScope
        , socket
        , $log
    ) {

        socket.on('send:version', function (data) {
            $log.log('send:version', data);
            $scope.version = data.version;
        });

        socket.on('send:time', function (data) {
            $log.log('send:time', data);
        });

        $scope.$watch('version', function(newVal, oldVal){
           $log.log('version', newVal, oldVal);
        });

        $scope.$on('socket:error', function (ev, data) {
            $log.log('socket:error', ev, data);
        });
}]);

1 个答案:

答案 0 :(得分:3)

所以问题是我仍在节点的app.js中使用app.listen(port)

我需要将其更改为server.listen(port, callback)并且一切都已开始工作:)

参考:http://net.tutsplus.com/tutorials/javascript-ajax/real-time-chat-with-nodejs-socket-io-and-expressjs/