Angular with socket io在页面更改时发出消息(无重新加载)

时间:2015-05-07 14:52:15

标签: javascript angularjs node.js socket.io

所以我现在正在设置我的节点服务器它看起来像这样:

    var multer = require('multer');
var express = require('express');
var app = express();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var cookieParser = require('socket.io-cookie-parser');
var moment = require('moment');
var mysql = require('mysql');
var users = {};
var message = "";
io.use(cookieParser());

var connection = mysql.createConnection({
    host: 'localhost',
    user: 'user',
    password: 'pass',
    database: 'myDb',
    port: 3306
});
connection.connect();

io.on('connection', function(socket)
{

    socket.on('loadUserDetails', function(userDetails){

        console.log(userDetails);

    });

    socket.on('browserClose', function(msg)
    {
        console.log('this user has disconnect: ');
    });
});


http.listen(8105, function(){
    console.log('listening on *:8105');
});

现在,在我的角度应用程序中,我有以下服务:

 app.factory('clientSocket', function (socketFactory) {
    var myIoSocket = io.connect('http://localhost:8105');

    var clientSocket = socketFactory({
        ioSocket: myIoSocket
    });

    return clientSocket;
});

然后我有HeaderController这个控制器应用于每个页面,因为它控制我的模板的头部区域:

    app.controller('HeaderController', ['$http', '$scope','$sessionStorage', 'apiUrl','$log','Session','api','clientSocket',  function ($http, $scope, $sessionStorage,apiUrl, $log, Session, api,clientSocket) {
    clientSocket.forward('someEvent', $scope);
    clientSocket.emit('loadUserDetails', $sessionStorage.activeUser.user);
    $scope.$on('clientSocket:someEvent', function (ev, data) {
        $scope.theData = data;
    });

}]);

现在问题。

每次我更改页面(不重新加载)

clientSocket.emit('loadUserDetails', $sessionStorage.activeUser.user);
每次都会调用

所以我的问题是如何处理这类案件?

0 个答案:

没有答案