对 AngularJS 中 $resource 调用的结果数组进行排序

Sorting an array that is the result of a $resource call in AngularJS

我正在尝试获取 API 调用的结果并将其保存到 $scope.segments,以便稍后我可以使用 $scope.segments.sort()

对数组进行排序

但是,由于 $scope.segments = SegmentsService.getSegments(jobId); 执行异步调用,因此 $scope.segmentsundefined 并且排序永远不会起作用。

整整一天都在为此苦苦挣扎。我该如何解决这个问题?

这是我的控制器:

angular.module('appApp')
  .controller('MainCtrl', function ($scope, $routeParams, $filter, JobsFactory, SegmentsFactory, SegmentsService) {

    var jobId = $routeParams.id;

    // gets the segments from the API
    $scope.segments = SegmentsService.getSegments(jobId);

    // returns 'undefined', because $resource has not populated the 'segments' array yet
    console.log($scope.segments);

    // returns "TypeError: Cannot read property 'sort' of undefined", because $scope.segment doesn't exist (yet)
    $scope.segments.sort(function(a, b) {
      return a.sequence - b.sequence;
    });

  });

这是我的服务:

angular.module('appApp')
  .service('SegmentsService', function (SegmentsFactory) {

    var segments = [];

    this.getSegments = function(jobId) {
      SegmentsFactory.query({ job_id: jobId }).$promise.then(function(data) {
        segments = data;
        return segments;
      }, function(err) {
        //fail
      });
    };

  });

最后,这是我的工厂:

angular.module('appApp')
  .factory('SegmentsFactory', function ($resource) {
    return $resource('http://localhost:3000/api/v1/segments/:id');
  });

您需要了解 promise 的工作原理:)

就此而言,我是 Promises in AngularJS, Explained as a Cartoon 的忠实粉丝:)

这是您的用例的工作代码。

// service: return the promise
.service('SegmentService', function (...) {    
     this.getSegments = function(jobId) {
         return SegmentsFactory.query({ job_id: jobId }).$promise;
     };
});

// controller
.controller('MainCtrl', function (...) {
    SegmentsService.getSegments(jobId).then(function(segments) {
        segments.sort(function(a, b) { return ...; });
        $scope.segments = segments;
    });

});