如何从AngularJS中的后续请求中正确存储本地数组
How to Store Local Arrays Properly from subsequent requests in AngularJS
我想要一个本地数组来存储"最后的邮件"(收件箱视图)。在我的服务中,我做了一个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));
}
});
})
相关文章:
- Meteor会话变量未存储数组
- 在Javascript的Textbox中存储数组中的值
- 如何保留输入复选框值的存储数组
- 如何在 localStorage 中存储数组
- 如何在打包的 chrome 应用中本地存储数组
- 如何在 html5 的本地存储对象中存储数组
- 需要循环访问 json 数据的本地存储数组中存储的 json 对象
- 在 Javascript 中创建存储数组,并在每次单击时推送元素 ID
- 根据选中的复选框存储数组元素
- 如何存储数组javascript
- 存储数组在Chrome扩展
- 什么是最有效的方式来存储数组从PHP到JS/jQuery,这样它是可重用的
- Javascript存储数组值
- 存储数组到Cookie Jquery
- Ruby在遍历函数时尝试存储数组元素
- 如何从mongodb的形式存储数组
- 如何在html中打印存储在本地存储数组中的值
- 使用Firebase存储数组
- 获取字符串格式的MySQL存储数组并转换为JSON对象的数组
- 在html attr中存储数组值的最佳实践