javascript - angularjs - 顺序调用执行 ngResource http post 请求的函数

标签 javascript angularjs http-post ngresource

这是要执行的函数的大纲和 http post 请求以从表中获取所有条目。这个函数是在我的 Controller 中定义的。

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

我需要为不同的表名依次调用这个函数。我试过像这样简单地调用它两次。

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

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

最佳答案

您需要从您的函数中返回 promise ,即。即:

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

然后,您可以使用返回的 promise 链接您的调用:

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

顺便说一句 $resource examples可能会帮助你更好地理解它。如果你需要管理很多链式 promise ,你应该看看 $q.all .

关于javascript - angularjs - 顺序调用执行 ngResource http post 请求的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51014812/

相关文章:

javascript - 将 javascript 对象序列化为 json 并返回

javascript - 主干提取 - "url"必须指定属性或函数错误

javascript - 单页应用程序上的 Alexa/similarWeb 流量跟踪?

http-post - 如何在 Fiddler 中创建 Post 请求

javascript - 在 Promise 中操作数据并在服务函数中返回它 - AngularJS

angularjs - Protractor 测试: Can someone tell me what I'm doing wrong with Require?

angularjs - angularjs http post方法将数据作为查询字符串发送?

javascript - Brave 浏览器的事件监听器/.getElementById 问题

javascript - react : Pass State To Siblings

javascript - 如何在 lightGallery 中动态更改图像 url