如何调用$http在angularJS顺序?但是我需要根据第一个$http的响应调用它第二个$http

How to call $http in angularJS sequentially? But I need to call it second $http based on response of first $http

本文关键字:http 调用 第一个 第二个 响应 何调用 angularJS 顺序      更新时间:2023-09-26

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

最好的选择是在请求中使用.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

你可以这样做:

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