代码之家  ›  专栏  ›  技术社区  ›  osanger

角度相关的$http请求

  •  0
  • osanger  · 技术社区  · 6 年前

    $http -方法返回一个承诺,但我必须依赖此数据来发出另一个请求。

    var data =
        "q=" + term
        "&timestamp=" + latest
    
    $http({
            method: 'POST',
            url: url,
            data: data
        }).then(
            function(response) {
                let dataList = response.data.list; 
                if(dataList.length > 50)
                   /*TODO: new query with other timestamp-value*/
                return dataList ;
    
            },
            function(response) {
                if(shouldLog){
                    console.log("[DebuggingService] " + response);
                }
            }
        );
    

    是否有一种方法可以根据以前的请求组合多个http请求?

    没有分页。因此,必须更改时间戳值。(获取响应的最新时间戳)

    2 回复  |  直到 6 年前
        1
  •  1
  •   Jimenemex    6 年前

    为什么不这样做:

    var data =
      "q=" + term + "&timestamp=" + latest;
    
    var amounts = 2;
    url = 'https://api.github.com/search/repositories?q=topic:ruby+topic:rails';
    
    call(url, data, checkForMore);
    
    function call(url, data, callback) {
      $http({
        method: 'POST',
        url: url,
        data: data
      }).then(function(data){
        console.log(data);
        console.log('------------');
        callback(data);
      });
    }
    
    function checkForMore(data){
        if (amounts > 0){
            amounts -= 1;
          var newData = "q=" + term +
                                        "&timestamp=" + data.SomehowGetLastestTimestamp;
          call(url, newData, checkForMore);
        } else {
            // Save it maybe?
        }
    }
    

    基本上,有一个在 .then 匿名函数。然后您可以传入数据并检查是否需要调用它。(根据您的情况)。如果你这样做了,那就打电话给 call 再次运行,但更新数据。

        2
  •  1
  •   charlietfl    6 年前

    then() 返回另一个请求或承诺

    function getData(term, time, res = []) {
    
      var data = "q=" + term + "&timestamp=" + time
      // return the $http promise
      return $http({
        method: 'POST',
        url: url,
        data: data
      }).then(function(response) {
        let dataList = response.data.list;
        // merge new data into final results array
        res = res.concat(dataList);
    
        if (dataList.length > 50) {
           const timeStampFromResponse = //????
          // return new request promise
          return getData(term, timeStampFromResponse, res)
        }
        // return final array
        return res;
    
      })
    }
    
    getData(term, latest).then(function(results) {
      // all results available here
    }).catch(function(response) {
      if (shouldLog) {
        console.log("[DebuggingService] " + response);
      }
    })