angularjspaginationangularjs-resource

How do i deal with server pagination with ngResource?


My scenario is that I want to use ngResource to retrieve lists of files from Google Drive. Drive paginates its results via the inclusion of a nextPageToken within the JSON response, null signifying no more results.

I need a promise or callback that refers to the completion of all pages, rather than after each page. Is there an elegant way for ngResource to handle this?


Solution

  • I don't think ngResource will inherently do anything like this for you by default, but you can do it by using a recursive closure and calling the ngResource inside it until you get all the data you are after.

    var dataSet = [];
    function getAllData(){
      var files = $resource('your url');
      files.get(function(data){
        if (data){
          dataSet.push(data); //or whatever   
          getAllData();
        }
      })();
    }
    

    Here is the tested version with actual Google Drive semantics

    getAllFiles(nextLink:string){
        var self = this;
        if (nextLink) {
            var files = self.refs.resource(nextLink);
        } else {
            var files = self.refs.resource(this.DRIVE_URL);
        }
        files.get(function(data){
            console.log("fetched "+data.items.length);
            self.allFiles.push(data['items']);
            if (data['nextLink']){
                self.getAllFiles(data['nextLink']);
            }
        });
    }