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

问题描述 投票:0回答:3

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

它应该如何运作。

例如我首先打电话

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

回复是:

{
   skip=10
},

比我打电话

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

跳过 20 的回应是

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

我需要停在那里。但是当我收到“跳过”响应时,我必须重复请求,并以将跳过添加到下一个请求的方式重复它们。

谢谢

angular rxjs angular2-observables
3个回答
3
投票

根据描述,听起来您实际上是要“分页”同一查询,而不是链接多个相关查询。为此,您可以使用

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

0
投票

您可以通过 FlowTestAI 使用简单的拖放操作轻松构建 API 请求链https://github.com/FlowTestAI/FlowTest

它不仅可以让您链接请求,还可以帮助您添加额外的逻辑,就像您的情况一样,当消息等于“您到达末尾”时,您可以结束链接


-1
投票

如果您没有太多调用,那么您可以将它们作为单独的方法链接在一起,如下所示。这将允许您更改返回的数据并在每个阶段对其进行操作:(我正在解释代码,所以如果它在语法上不是 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 循环中),那么您必须将它们添加到排队类型系统中。

© www.soinside.com 2019 - 2024. All rights reserved.