简体   繁体   English

当来自多个http调用的数据异步时,如何对列表进行排序

[英]How to sort a list when the data is async from multiple http calls

I need to loop a list of URLs and display the results in one table. 我需要循环访问URL列表,并将结果显示在一个表中。 It seems like orderBy does not work because list($scope.versions) is from multiple HTTP calls and HTTP is asynchronous. 似乎orderBy不起作用,因为list($scope.versions)来自多个HTTP调用,并且HTTP是异步的。

Controller: 控制器:

var callApi = function (app, env, index, url) {
  $http.get(url).
     success(function(data) {
       data.pos=index;
       $scope.versions[app].push([data]);
     }).
     error(function(data, status) {
       var errorData = {};
       errorData.pos=index;
       $scope.versions[app].push([errorData]);
     });
   console.log($scope.versions);
 };

HTML: HTML:

<tbody>
  <tr ng-repeat="(k,v) in versions">
    <td>{{k}}</td>
    <td ng-repeat="item in v |  orderBy:'item[0].pos'" 
      ng-class="{'danger': item[0].error === true, 'success': item[0].error === false}">
      [{{item[0].pos}}]
    </td>
  </tr>
</tbody>

It's a little unclear what exactly you're trying to do and it's unclear what your data looks like, but in a general sense, you can always sort your data as it comes in. 不清楚您到底要做什么,也不清楚数据是什么样,但是从一般意义上讲,您总是可以对数据进行排序。

For example, you could use splice() to insert the data where it needs to be in the array: 例如,您可以使用splice()将数据插入数组中所需的位置:

$scope.items = [];
var urls = [ <some urls> ];
urls.forEach( function (url) {
  $http.get(url)
    .success( function (data) {
      var position = getPosition(data);
      $scope.items.splice(position, 0, data);
    })
    .error( function (data, status) {
      // Handle the error case
    });
});

function getPosition (data) {
  // Some code to find where the element
  // should be inserted into the array
  return position;
}

Or, you could sort the data every time after your add new data: 或者,您可以在添加新数据后每次对数据进行排序:

$scope.items = [];
var urls = [ <some urls> ];
urls.forEach( function (url) {
  $http.get(url)
    .success( function (data) {
      $scope.items.push(data);
      $scope.items.sort(itemsCompareFunc)
    })
    .error( function (data, status) {
      // Handle the error case
    });
});

function itemsCompareFunc (a, b) {
  // Some logic to compare both items
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM