我有Websockets使用的应用程序。在服务器上更改一些数据后,我从websocket得到一些消息,改变了什么,需要更新表中的数据。我从websocket获取数据,发送get请求获取数据,并用数据更新我的作用域,但我没有看到表中的变化。在美元范围。ordersList i保存从服务器获取的日期。
My websockets service:
var services = angular.module('services', []);
services.factory('EventService', ['$cookies',
function($cookies) {
var service = {};
service.connect = function() {
if (service.ws) {
return;
}
var ws = new WebSocket("ws://" + window.location.host + "/events/");
ws.onopen = function() {
ws.send(JSON.stringify({
type: "auth",
token: $cookies.token
}));
console.log("Succeeded to open a conection");
};
ws.onerror = function() {
console.log("Failed to open a connection");
};
ws.onmessage = function(message) {
var obj = JSON.parse(message.data);
if (obj.result) return;
if (obj.id) {
setTimeout(function() {
service.callback(obj);
}, 1000)
}
};
service.ws = ws;
};
service.subscribe = function(callback) {
service.callback = callback;
};
return service;
}
]);
如何在我的控制器中使用它:
EventService.subscribe(function(msg) {
console.log('msg', msg);
var item = $.grep($scope.ordersList, function(item) {
return item.id == msg.id
})
if (item.length > 0) {
item[0].status = msg.status
} else {
$scope.ordersList.push(msg);
}
$scope.$apply();
});
$scope.getOrders();
EventService.connect();
和我的模板:
<tr item="parameter" ng-repeat="item in ordersList">
<td>{{item.id}}</td>
<td>{{item.symbol}}</td>
</tr>
您需要包装服务。$rootScope中的回调。申请进入角消化循环。检查以下内容以获得概念:http://www.html5rocks.com/en/tutorials/frameworks/angular-websockets/