AngularJS在GET请求时向数组推送新项

AngularJS pushing new items to an array on GET request

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

我正在使用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
}

然而,这只是当你真的需要为这些三角洲做些什么的时候;如果你所需要做的只是保持你的列表最新,只需替换旧的列表。