繁体   English   中英

用户更新时在AngularJs中使用socket.io时出错

[英]Errors when using socket.io in AngularJs on user updates

嗨,我想在用户更改首选语言时自动对文章列表进行更新。

我尝试执行此操作的方法是,每当用户在数据库中进行更改时,都会更新IO socket

但是,我的努力似乎并不成功,我也不知道为什么。

由于我是socket.io的新手,所以我想在这里向编码神寻求帮助。

愿软件与您同在^^

PS:该项目是Angular fullstack项目,由Yeoman Angular fullstack


编码时间!


客户端/组件/articlebar/articlebar.controller.js

'use strict';

angular.module('unityAcademyApp')
.controller('ArticlebarCtrl', function ($scope, $location, Auth, socket) {
  $scope.articles = {};

  function populateArticles(){ 
       ...
        Some functionality where $scope.articles are set
        ...
    };

    socket.syncUpdates('user', $scope.articles, function() {
        console.log('hit');
        populateArticles();
    });
});


客户端/组件/套接字/socket.service.js

/* global io */
'use strict';

angular.module('unityAcademyApp')
  .factory('socket', function(socketFactory) {

    // socket.io now auto-configures its connection when we ommit a connection url
    var ioSocket = io('', {
      // Send auth token on connection, you will need to DI the Auth service above
      // 'query': 'token=' + Auth.getToken()
      path: '/socket.io-client'
    });

    var socket = socketFactory({
      ioSocket: ioSocket
    });

    return {
      socket: socket,

      /**
       * Register listeners to sync an array with updates on a model
       *
       * Takes the array we want to sync, the model name that socket updates are sent from,
       * and an optional callback function after new items are updated.
       *
       * @param {String} modelName
       * @param {Array} array
       * @param {Function} cb
       */
      syncUpdates: function (modelName, array, cb) {
        cb = cb || angular.noop;

        /**
         * Syncs item creation/updates on 'model:save'
         */
        socket.on(modelName + ':save', function (item) {
          var oldItem = _.find(array, {_id: item._id});
          var index = array.indexOf(oldItem);   // this is line 39
          var event = 'created';

          // replace oldItem if it exists
          // otherwise just add item to the collection
          if (oldItem) {
            array.splice(index, 1, item);
            event = 'updated';
          } else {
            array.push(item);
          }

          cb(event, item, array);
        });

        /**
         * Syncs removed items on 'model:remove'
         */
        socket.on(modelName + ':remove', function (item) {
          var event = 'deleted';
          _.remove(array, {_id: item._id});
          cb(event, item, array);
        });
      },

      /**
       * Removes listeners for a models updates on the socket
       *
       * @param modelName
       */
      unsyncUpdates: function (modelName) {
        socket.removeAllListeners(modelName + ':save');
        socket.removeAllListeners(modelName + ':remove');
      }
    };
  });


服务器/配置/socketio.js

/**
 * Socket.io configuration
 */

'use strict';

var config = require('./environment');

// When the user disconnects.. perform this
function onDisconnect(socket) {}

// When the user connects.. perform this
function onConnect(socket) {
    // When the client emits 'info', this listens and executes
    socket.on('info', function (data) {
        console.info('[%s] %s', socket.address, JSON.stringify(data, null, 2));
    });

    // Insert sockets below
    require('../api/translation/translation.socket').register(socket);
    require('../api/comment/comment.socket').register(socket);
    require('../api/article/article.socket').register(socket);
    require('../api/language/language.socket').register(socket);
    require('../api/thing/thing.socket').register(socket);
    require('../api/user/user.socket').register(socket);
}

module.exports = function (socketio) {
    // socket.io (v1.x.x) is powered by debug.
    // In order to see all the debug output, set DEBUG (in server/config/local.env.js) to including the desired scope.
    //
    // ex: DEBUG: "http*,socket.io:socket"

    // We can authenticate socket.io users and access their token through socket.handshake.decoded_token
    //
    // 1. You will need to send the token in `client/components/socket/socket.service.js`
    //
    // 2. Require authentication here:
    // socketio.use(require('socketio-jwt').authorize({
    //   secret: config.secrets.session,
    //   handshake: true
    // }));

    socketio.on('connection', function (socket) {
        socket.address = socket.handshake.address !== null ?
            socket.handshake.address.address + ':' + socket.handshake.address.port :
            process.env.DOMAIN;

        socket.connectedAt = new Date();

        // Call onDisconnect.
        socket.on('disconnect', function () {
            onDisconnect(socket);
            console.info('[%s] DISCONNECTED', socket.address);
        });

        // Call onConnect.
        onConnect(socket);
        console.info('[%s] CONNECTED', socket.address);
    });
};


服务器/ api /用户/ user.socket.js

/ ** *模型更改时向客户端广播更新* /

'use strict';

var User = require('./user.model');

exports.register = function(socket) {
  User.schema.post('save', function (doc) {
    onSave(socket, doc);
  });
  User.schema.post('remove', function (doc) {
    onRemove(socket, doc);
  });
}

function onSave(socket, doc, cb) {
  socket.emit('user:save', doc);
}

function onRemove(socket, doc, cb) {
  socket.emit('user:remove', doc);
}

到目前为止遇到的错误

到目前为止,运行代码时出现以下错误

TypeError: array.indexOf is not a function
    at Socket.<anonymous> (socket.service.js:39)
    at socket.js:24
    at angular.js:17782
    at completeOutstandingRequest (angular.js:5490)
    at angular.js:5762
        (anonymous function)        @ angular.js:12416
        $get                        @ angular.js:9203
        (anonymous function)        @ angular.js:17785
        completeOutstandingRequest  @ angular.js:5490
        (anonymous function)        @ angular.js:5762

我不确定为什么会收到该错误,但是我想我知道为什么您的数据没有更新。

您必须将回调函数包装在$timeout函数内,以触发您的更改。 例如,您可以这样做:

$timeout(function(){
    cb(event, item, array);
}, 0);

请记住在套接字工厂中包含$timeout指令。

“无得分”是什么意思? 我不确定'undescore',但是我想这是'this'的别名。 我认为您应该初始化var _ = this。

我只是在猜。

我发现了问题。

该错误是由于它在文章列表中寻找用户而导致的,由于没有匹配项而返回undefined 因此,解决方案是更改client/ components/ articlebar/ articlebar.controller.js

socket.syncUpdates('user', $scope.articles, function() {
    console.log('hit');
    populateArticles();
});

socket.syncUpdates('user', $scope.users, function() {
    console.log('hit');
    populateArticles();
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM