我有一个websocket连接,可以在angularjs中提取json数据。基本思想是代码:数组中的5个项目是问题和代码:数组中的6个项目是删除问题的请求。
收到的第一个jSON数据如下所示:
[{"code":1,"timestamp":"2017-07-11T21:00:16.655706556Z","text":"Welcome to the listening pool, total clients 1","uuid":"51c7d6c7-8b6a-4b39-a460-343480e6cd23"},{"code":5,"timestamp":"2017-07-11T21:00:18.736695286Z","text":"By trying we can easily learn to endure adversity. Another man's, I mean.\n\t\t-- Mark Twain\n","uuid":"9046a275-ada8-415a-9dd3-37bdbfc43f75"}]
代码:然后将5个项目发布到问题队列中的页面。来自websocket的第二次更新将包括代码:6以删除已发布的问题(代码:5)。我正在使用uuid值来查找匹配项并删除问题。
[{"code":1,"timestamp":"2017-07-11T21:00:16.655706556Z","text":"Welcome to the listening pool, total clients 1","uuid":"51c7d6c7-8b6a-4b39-a460-343480e6cd23"},{"code":5,"timestamp":"2017-07-11T21:00:18.736695286Z","text":"By trying we can easily learn to endure adversity. Another man's, I mean.\n\t\t-- Mark Twain\n","uuid":"9046a275-ada8-415a-9dd3-37bdbfc43f75"},{"code":6,"timestamp":"2017-07-11T21:00:23.870193214Z","uuid":"9046a275-ada8-415a-9dd3-37bdbfc43f75"}]
我遇到的问题是它只删除了第一个副本。当从Web套接字接收到更多数据时,它会将旧数据已经删除的项目放回来。
非常感谢任何帮助。
这是我的角度代码:
<section ng-controller="WaitingRoom">
<ul ng-repeat="data in MyData.collection | orderBy: '-timestamp' track by $index" ng-show="data.code == 5 && data.uuid != MyData.collection[$index].uuid">
<li id="code"> Code: {{ data.code}} </li>
<li> Timestamp: {{ data.timestamp | date:'medium'}} </li>
<li> Question: {{ data.text}} </li>
<li id="uuid"> ID: {{ data.uuid}} </li>
</ul>
</section>
angular.module('MY_APP', ['ngWebSocket'])
//
.factory('MyData', function($websocket) {
// Open a WebSocket connection
var dataStream = $websocket('ws://website.com/data');
var collection = [];
dataStream.onMessage(function(message) {
collection.push(JSON.parse(message.data));
});
var methods = {
collection: collection,
get: function() {
dataStream.send(JSON.stringify({ action: 'get' }));
}
};
return methods;
})
.controller('WaitingRoom', function ($scope, MyData) {
$scope.MyData = MyData;
});
答案 0 :(得分:0)
您可以在angularjs中使用名为unique
的过滤器。
示例如下:
ng-repeat="data in array | unique:fieldName"
{{data }}
答案 1 :(得分:-1)
如果您不介意使用像Underscore.js这样的东西,它可以从数组中删除重复项。
答案 2 :(得分:-1)
我想我得到了它的工作。不确定这是否是最好的方法,但它似乎工作。任何有关清理或更好解决方案的建议都将不胜感激。
dataStream.onMessage(function(message) {
var data = collection.push(JSON.parse(message.data));
var data = (JSON.stringify(collection));
var data = Object(collection);
for (var i = 0; i < data.length; i++) {
var uuid1 = collection[i].uuid;
// console.log(uuid1);
for (var j = 0; j < data.length; j++) {
var uuid2 = collection[j].uuid;
// console.log(uuid2);
if (i !=j){
if (uuid1 == uuid2){
console.log("Duplicate found: " + uuid1);
collection.splice(i);
collection.splice(j);
}
else console.log("No Duplicates");
}
}
}
});