简要背景:- 我正在构建一个社交网站,并使用 MongoDB 存储状态和用户。例如,你有这样的状态
{
"status" : "Hello world.",
"profileURL" : "ac271a307",
"comments" : [ ],
"time" : "2013-10-28T22:25:24.278Z",
"active" : true,
"owner" : DBRef("users", "[email protected] /cdn-cgi/l/email-protection"), // MongoDB Reference to the users Collection
"_id" : ObjectId("526ee454da46f33bf8000002")
}
现在在 Angular 上做;
<li ng-repeat="status in statuses | isUserStatus track by status['_id']" ng-show="status.active" class="user-status-bland">
// In here i display the users data and the status itself.
</li>
注意:这一切都很完美
但问题就在这里。我使用 Websockets 自动更新并将新状态添加到 $rootScope.statuses 中。
socket.on('new status', function(status) {
$timeout(function() {
$rootScope.$apply(function() {
// stack the new status at the top of all statuses.
$rootScope.statuses.unshift(status);
});
}, 0);
})
现在,如果您在 websocket 回调中执行“status”的 console.log(),我会得到状态并且它会出现两次。从某种意义上说,websocket 被发送了两次(我无法控制)。因此,当将其放入“$rootScope.statuses”中时,我就会收到错误“错误:[ngRepeat:dupes] 不允许在转发器中重复。使用‘track by’表达式来指定唯一键。”这没有意义,因为我实际上正在使用 $track by status['_id']