了解yeoman的fullstack套接字服务
了解yeoman的fullstack提供的套接字服务,我有点麻烦。 我提供了一个如何使用syncUpdate函数的示例,添加了modelPlacevariables来知道函数的调用方式。
所以,这是一个伪工作空间模型
var working_spaceSchema = new Schema({ ... users: [], todos: [{name:String,info:String,priority:Number,id:Number}], chat: [{content:String,poster:String,creation:Date}], ... });
以及我在angular度控制器中调用套接字服务的方式:
$http.get('/api/works/' + $location.$$path.substr(7)) .success(function(data) { $http.post('/api/works/' + $location.$$path.substr(7) + '/connexion', {type:0}); $scope.chats = data; socket.syncUpdates('work', 'chat', $scope.chats, function(event, chat, chats) { $scope.chats = chats; }); });
为了提醒,这里是套接字服务文件。 你可以看到modelPlacevariables,它让我知道我必须从schema.post中同步什么:
'use strict'; angular.module('yoyoApp') .factory('socket', function(socketFactory) { // socket.io now auto-configures its connection when we ommit a connection url var ioSocket = io(null, { // Send auth token on connection, you will need to DI the Auth service above // 'query': 'token=' + Auth.getToken() }); 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 */ // Should consider givin' $state.params.id to syncUpdates // check currentUser.state and trigger notification IF =/= from update current state syncUpdates: function (modelName, modelPlace, array, cb) { cb = cb || angular.noop; /** * Syncs item creation/updates on 'model:save' */ socket.on(modelName + ':save', function (item) { var event = 'created'; if (modelPlace == 'todo_list') array = item.todos; else if (modelPlace == 'chat') array = item.chat; cb(event, item, array); }); /** * Syncs removed items on 'model:remove' * JE CROIS QUE CE N'EST PAS NECESSAIRE */ 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, modelPlace) { socket.removeAllListeners(modelName + ':save:' + modelPlace); socket.removeAllListeners(modelName + ':remove:' + modelPlace); } }; });
添加到“ioSocketvariables”的问题,我想知道我应该如何使用syncUpdate函数的最佳实践是什么(我的不是,显然…)。
感谢你们 !
“到DI”意味着使用dependency injection来获取Auth服务。Auth是Angular-Fullstack提供的另一种服务。 只需在其中一个控制器的function定义中包含对Auth的引用即可。 例如:
angular.module('testSuiteUi2App') .controller('JobCtrl', function ($scope, Auth, socket) { $scope.myVar = 'Hello!'; }
我在代码中遇到了一些麻烦,但这是我想为socketUpdates调用所需的。
socket.syncUpdates('chat', $scope.chats);
这就告诉系统你要同步一个叫做'chat'模型types的$ scope.chats的数组。 你也可以用callback来做到这一点:
socket.syncUpdates('chat', $scope.chats, function(event, item, object) { $scope.chats = item; // item contains the updated array });