AngularJS在GET请求时向数组推送新项
AngularJS pushing new items to an array on GET request
我正在使用ionic框架在我的应用程序上实现通知功能。它的工作方式是向rest api发出get请求,该api返回一组通知。但这似乎太多了,因为我每次都要对同一个列表发出请求,所以我想把第一个请求存储在本地变量中(使用ngStorage),然后在下一个请求中提取新项目。。这个解决方案可能吗?如果是的话,你能举例说明如何进行吗
/*示例1 Json的第一个请求,我将把列表存储在$localStorage变量*/中
[{id:1, notification:'notif A'},
{id:2, notification:'notif B'}]
/*对于第二个请求,我只想将get"id:3"推送到我的$localStorage,这怎么可能*/
[{id:1, notification:'notif A'},
{id:2, notification:'notif B'},
{id:3, notification:'notif C'}]
最好让服务器只向您传递新的通知,前提是你可以在请求中传递一些信息,说明你已经拥有的最新通知是什么(例如,你的请求可以包含一个查询参数,如last_id=<id>
,你的服务器使用它来过滤旧的或比它旧的通知;这假设id
的值与通知期限相关;还有其他服务器端解决方案)。
如果您无法控制服务器,最快的方法就是用新列表替换整个列表。我认为找到三角洲并没有什么好处;添加它们。
然而,如果您出于另一个原因需要delta(例如,您需要根据每个新通知的内容对其运行一些操作),那么一种选择是将您的通知存储为对象而不是数组:
// notifications are keyed by ID
var notifications = {};
// load notifications from storage if needed
// newList is the array of new notifications
// newNotificationFcn is an optional callback function, which
// takes the new notification as its only argument
function updateNotifications(newList, newNotificationFcn) {
var doNotify = (typeof newNotificationFcn === 'function');
newList.forEach(function(curr) {
if (!notifications.hasOwnProperty(curr.id) {
// this is a new notification; do something
if (doNotify) {
newNotificationFcn(curr);
}
notifications[curr.id] = curr;
}
});
// store away notifications as needed
}
然而,这只是当你真的需要为这些三角洲做些什么的时候;如果你所需要做的只是保持你的列表最新,只需替换旧的列表。
相关文章:
- Javascript/jQuery:如何从数组的项中获取排列
- 使用名称/值从 json 数组添加项
- 在 JavaScript 中,当循环通过 FOR 循环时,如何将数组中项的值传递给匿名函数
- 如何按属性从可观察数组返回项
- 数组列表项搜索
- 对可观察数组中项的属性进行自定义绑定,如何访问该项
- knockoutjsforeach数组选择项值绑定
- 检查字符串中的数组匹配项并继续检查
- 更新数组的项
- BackboneJS如何删除Model数组的项
- 从数组随机项-不能找到变量:getElementById
- Splice()不更新knockout.js中数组的项顺序
- 如何获取数组中项目的id
- 检查多维数组中项旁边的位置
- 访问压入数组的项
- 在Angular中基于ng-repeater索引查找数组的项
- 为什么它在创建json对象时创建数组新数组
- RethinkDB:订阅数组中项的更改
- JavaScript:在另一个数组中插入数组's项
- 如何添加数组新键值(javascript)