angularjs - 依次调用执行 ngResource http post 请求的函数

angularjs - Sequentially call function that performs ngResource http post request

这是要执行的功能的概述,http post 请求从 table 获取所有条目。这个函数是在我的控制器中定义的。

$scope.getAllData = function (tableName) {
  var allDataResults = $resource('/getAllDataForTable', {}, {
    save: {
      method: 'POST',
      timeout: 6000
    }
  });
  allDataResults.save($scope.all_data_input, function (response) {
    //Do stuff with response
    }
  });
};

我需要为不同的 table 名称顺序调用此函数。我试过像这样简单地调用它两次。

$scope.getAllData(tableName1);
$scope.getAllData(tableName2);

第二个回答正确,但第一个回答不正确。每个响应都包含一个列表,并且第二个响应的列表的大小强加于第一个响应,导致响应不正确。如何正确链接这 2 个 post 请求请求?

您需要 return 函数中的承诺,即。即:

$scope.getAllData = function (tableName) {
  var allDataResults = $resource('/getAllDataForTable', {}, {
    save: {
      method: 'POST',
      timeout: 6000
    }
  });
  return allDataResults.save($scope.all_data_input, function (response) {
    //Do stuff with response
    }
  });
};

然后,您可以使用 returned 承诺链接您的调用:

$scope.getAllData(tableName1).$promise.then(function() {
  $scope.getAllData(tableName2);
});

顺便说一句 $resource examples might help you understand it better. If you need to manage a lot of chained promises, you should look at $q.all