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

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

本文关键字:结果 排序 调用 AngularJS 中对 resource      更新时间:2023-09-26

我试图获得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');
  });

你需要了解承诺是如何工作的:)

我是AngularJS中的Promises的超级粉丝,就像漫画一样解释:)

这是你用例的工作代码。

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