Chain API 取决于先前请求的响应的 http 请求

Chain API http request that depends on response of previous request

我正在尝试实现将重复 X 次并在上次请求没有响应时停止的链式 http 请求。

它应该如何工作。

例如我先调用

http://example.com/?skip=0

响应是:

{
   skip=10
},

比我叫

http://example.com/?skip=10
...
http://example.com/?skip=20

并且在跳过 20 时响应是

{
  "message" : "You reach the end"
}

我需要到此为止。但是,当我收到 "skip" 响应时,我必须重复请求,并按照我添加 skip 到下一个请求的方式重复它们。

谢谢

如果您没有太多调用,那么您可以将它们链接在一起作为单独的方法,如下所示。这将允许您更改返回的数据并在每个阶段对其进行操作:(我正在解释代码,如果它在语法上不是 100% 正确的话,我深表歉意)

$scope.call1 = function (values) {
   $.ajax({
        url: _url,
        method: 'GET'
    })
    .done(function (data) {
        ...do stuff with data...
        $scope.call2(data);
    })
};

$scope.call2 = function (values) {
   $.ajax({
        url: _url,
        method: 'GET'
    })
    .done(function (data) {
        ...do stuff with data...
        $scope.call3(data);
    })
};

$scope.call3 = function (values) {
   $.ajax({
        url: _url,
        method: 'GET'
    })
    .done(function (data) {
        ...do stuff with data...
        ...this is the end...
    })
}; 

然后用

开始
$scope.call1(params);

只有在前一个方法完成后,才会依次调用每个方法。 如果您确实有很多(即在一种 for 循环中),那么您必须将它们添加到队列类型系统中。

根据描述,听起来您实际上是想 "paginate" 同一个查询,而不是链接多个相关查询。为此,您可以使用 expand:

// Start with skip 
Observable.of({skip: 0})
  // Feeds the response resulting stream back into this function
  .expand((response) => {
    // Continue expanding if there is a skip parameter
    if (response.skip >= 0)
      return this.http.get(`http://example.com/?skip=${skip}`);
    // Stop expanding if there is no more data
    else
      return Observable.empty();
  }, 1 /* Limit the number of consecutive queries*/);