如何从AngularJS中的后续请求中正确存储本地数组

How to Store Local Arrays Properly from subsequent requests in AngularJS

本文关键字:存储 数组 请求 AngularJS      更新时间:2023-09-26

我想要一个本地数组来存储"最后的邮件"(收件箱视图)。在我的服务中,我做了一个GET请求,返回如下数据结构:

[{id:1, from_user:1, to_user:2, message:"bar", has_been_read:false}, 
{id:2, from_user:3, to_user:2, message:"foo", has_been_read:false}]

服务器只发送最后一条has_been_read==false的消息,这是服务的代码:

$scope.unreadMessages = []
$scope.GetUnreadMessages = function(){
      $localStorage.AllMessages.push($scope.unreadMessages)
       UserService.GetUnreadMessages()
            .success(function (data) {
              data = angular.fromJson(data);
              $scope.unreadMessages.push(data);
              }).
            error(function(error) {         
        //do something
          });
}
$scope.GetUnreadMessages()

假设在上面给出的json示例中,我读取了id:1,这导致has_been_read变为true。。在下一个请求中,它将只返回数据id:2,这是正确的。。但我的问题是新的请求数据取代了我所有的旧数据。所以我想做的是,即使我读到id:1,除非我删除了它,或者我有来自同一用户的新消息,我仍然想在我提出新请求时保留它。。我知道我的代码是错误的,只是不知道该怎么办。。

一种可能的解决方案是保存按from_user:分组的响应

.success(function(unreadMessages){
    angular.forEach(unreadMessages, function(unreadMessage){
        // if conversation from a user exists
        if(localStorage.getItem(unreadMessage.from_user)){
            var conversation = JSON.parse(localStorage.getItem(unreadMessage.from_user));
            conversation.push(unreadMessage);
            localStorage.setItem(unreadMessage.from_user, JSON.stringify(conversation));
        } else {
            var conversation = [];
            conversation.push(unreadMessage);
            localStorage.setItem(unreadMessage.from_user, JSON.stringify(conversation));
        }
    });
})