与分页集合工作时Angularjs承诺链 [英] Angularjs promise chain when working with a paginated collection

查看:162
本文介绍了与分页集合工作时Angularjs承诺链的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一个REST API,它提供了GET请求分页响应,像这样的工作

I'm working with a REST api that provides a paginated response for GET requests, like so:

{count: 43103
previous: null
next: http://ecoengine.berkeley.edu/api/photos/?page=2
results: [json objects....]
}

我想创建遵循接下来链接,直到加载所有数据的服务接下来变空。我卡在如何链承诺在这种情况下,并会AP preciate对如何进行任何帮助(这里的角/ JS新手)。我在这里跟我到目前为止得到plunker在这里 http://plnkr.co/edit/ySiQLvu9RNrKkQAoDmKh 。您可以从该code仅第2页检索数据的控制台消息看。谢谢你。

I would like to create a service that loads all the data by following the next link till next becomes null. I'm stuck on how to chain promises in this scenario and would appreciate any help on how to proceed (angular/js newbie here). My plunker with where i've gotten so far is here http://plnkr.co/edit/ySiQLvu9RNrKkQAoDmKh. You can see from the console messages that the code retrieves data from first 2 pages only. Thank you.

推荐答案

我试图做使用递归来解决这种情况下诺言链接。看到我的小提琴此处

I tried to do chaining of promises using recursion to solve this scenario. See my fiddle here

http://plnkr.co/edit/NPh6uQ2DgVuhVxUgHB6h?p=info

基本上递归上loadData做可以得到分页的数据。这是实施

Basically recursion done on loadData can get paged data. This is the implementation

var loadData = function(url) {
      var deferred = $q.defer();

      function loadAll() {
        $http.get(url)
           .then(function(d) {
                debugger;
                console.log('private http.get().then()');
                console.log(d);
                aggregateData.value.push(d.data.results);
                if(d.data.next) {
                   url=d.data.next;
                   loadAll();
                }
                else {
                   deferred.resolve(aggregateData.value);
                }
           })
      }
      debugger;
      loadAll();
      return deferred.promise;

 };

我用 aggregateData 数组,但你可以自由使用的loadData函数声明的数组。

I used the aggregateData array but you are free to use any array declared in the loadData function.

这篇关于与分页集合工作时Angularjs承诺链的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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