如何使用angularjs资源处理分页和计数? [英] How to handle pagination and count with angularjs resources?

查看:26
本文介绍了如何使用angularjs资源处理分页和计数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须为输出 JSON 的 API 构建一个 angularjs 客户端,如下所示:

I have to build an angularjs client for an API outputting JSON like this:

{
  "count": 10,
  "next": null,
  "previous": "http://site.tld/api/items/?start=4"
  "results": [
    {
      "url": "http://site.tld/api/items/1.json",
      "title": "test",
      "description": "",
      "user": "http://site.tld/api/users/4.json",
      "creation_datetime": "2013-05-08T14:31:43.428"
    },
    {
      "url": "http://site.tld/api/items/2.json",
      "title": "test2",
      "description": "",
      "user": "http://site.tld/api/users/1.json",
      "creation_datetime": "2013-05-08T14:31:43.428"
    },
    {
      "url": "http://site.tld/api/items/3.json",
      "title": "test3",
      "description": "",
      "user": "http://site.tld/api/users/2.json",
      "creation_datetime": "2013-05-08T14:31:43.428"
    }
  ]
}

我如何制作一个映射到这个的 $resource?如果我使用 isArray=false,我会将整个 blob 作为一个对象,可用于读取,但我不能对其调用 .put().如果我使用 isArray,它就不起作用.

How can I make a $resource that maps to this ? If I use isArray=false, I'll get the entire blob as one object, usable for reading, but I can't call .put() on it. If I use isArray, it just doesn't work.

有什么干净的方法可以做到这一点吗?或者我应该回到使用 $http 吗?

Is there any clean way to do this? Or should I go back to using $http?

推荐答案

您有几个选择.如果您可以更改服务器输出,则可以将元信息(计数、下一个、上一个)添加为标头值,而不是将它们添加到响应正文中.

You have a couple of options. If you can change the server output you could add the meta info (count, next, previous) as header values instead of adding them in the response body.

您的第二个选择是使用 transformResponse 转换响应.这在 angular v1.1.2 及更高版本(不稳定分支):

Your second option is to transform the response with transformResponse. This is available as a $response configuration in angular v1.1.2 and later (the unstable branch):

var Data = $resource('./data.json',{},{
  list:{isArray:true,method:'get',
    transformResponse: function (data, headers) {
      return JSON.parse(data).results; 
   }}
});

如果你不想使用不稳定的分支,也可以更改 $resource 使用的 $http:

If you don't want to use the unstable branch it is also possible to change the $http which $resource uses:

$http.defaults.transformResponse.push(function(data){
  if(data && data.results){
    return data.results;
  }
});

我用两个例子创建了一个 plunker:http://plnkr.co/edit/PmYotP0eo5k41Z6ZCxl4?p=preview

I've created a plunker with both examples: http://plnkr.co/edit/PmYotP0eo5k41Z6ZCxl4?p=preview

我不确定将元数据传递给应用程序其余部分的最佳方法是什么(如果需要的话).您可以将其附加到第一个结果中,或者将其添加为一个单独的对象 - 也许不那么优雅,但它会完成工作.

I'm not sure what the best approach for passing on the meta data to the rest of your application (if you need it). You could append it to the first result, or add it as a separate object - maybe not so elegant, but it'll get the job done.

这篇关于如何使用angularjs资源处理分页和计数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆