我有一個websocket連接,它以angularjs的方式提取json數據。基本思想是代碼:數組中的5個項目是問題和代碼:數組中的6個項目是刪除問題的請求。在angularjs中刪除重複的數組項目
收到看起來像這樣第一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"}]
我遇到的問題是,它只能刪除第一個副本。當從網絡套接字接收到更多數據時,它會將舊數據移回已刪除的項目。
任何幫助將不勝感激。
這是我的角度代碼:
<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;
});
你能只是'collection.push之前增加一個檢查(JSON.parse(message.data));'線檢查UUID,看它是否已經在收藏裏?如果不是,則添加它。否則 - 忽略,替換或刪除該項目。 –