如何在angularJS中依次调用$ http?但我需要根据第一个$ http的响应将其称为第二个$ http

时间:2016-10-06 03:40:02

标签: javascript angularjs http

我必须进行两次$ http调用,但第二次调用必须基于第一次响应(仅当出现任何错误时)。

2 个答案:

答案 0 :(得分:0)

最好的选择是在您的请求中使用.then()。当使用.then时,你可以传入多个将被调用的函数 - 第一个如果成功,第二个如果有错误。所以,它看起来像这样:

//First http call
$http.get('http://your-url.com')
  .then(function (trsponse) {
    //Call was successful; do something
  }, function (response) {
    //Call was unsuccessful; Grab whatever you need from the response and make your second http call:
    var data = response.data;
    var statusCode = response.status;
    var statusText = response.statusText;
    $http.get('http://your-second-url.com');  
  });

传递给你的函数的响应将包含这些属性:

 data – The response body
 status – The status code of the response (e.g. 404)
 headers – Headers on the response
 statusText – The text of the status of the response

答案 1 :(得分:0)

您可以这样做:

var promise1 = $http.get('firstUrl.com');

promise.then(
  function(payload) {
    $scope.movieContent = payload.data;
  })
  .catch(function (error) {
    secondUrl();
    console.log("Something went terribly wrong.");
  });

然后:

var secondUrl = function(){

   var promise2 = $http.get('secondUrl.com');

   promise2.then(
   // get the data and also other required functions
  );

}