How to handle pagination and count with angularjs resources?

后端 未结 4 438
闹比i
闹比i 2020-12-23 17:05

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

{
  \"count\": 10,
  \"next\": null,
  \"previous\": \"http://site.tld/api/items/?s         


        
4条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-23 18:02

    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.

    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; 
       }}
    });
    

    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;
      }
    });
    

    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.

提交回复
热议问题