如何在angularjs中使用第一个api的结果,进入第二个api调用

How to use result of first api, into second api call in angularjs?

本文关键字:api 结果 调用 第二个 第一个 angularjs      更新时间:2023-09-26

我想将第一个api的结果用于第二个api调用。场景是这样的,我想使用第一个api的结果,进入第二个api调用。如果我是正确的,那么我想要同步api调用(不确定)。我试着写下面的函数,但没有成功。function2在function1之前调用在函数2中,我们使用result1,它只有在函数2之前调用函数1时才出现,我该怎么做。

$scope.function1 = function(){
        var deferred= $q.defer();    
        $http.post(api1, data1)
        .success(function(response, status) {
          if (response.error == 0) {
            console.log(response.result);          
               $scope.result1=response.result;      
          }           
        }) ;    
        deferred.resolve('Success') ; 
        return deferred.promise;       
    };
    var promise =  $scope.addDefaultValue();
    promise.then(function(){
      $scope.function2();
    });
     $scope.function2=function(){
        var deferred = $q.defer();
        $http.post(api2,result1)
        .success(function(response, status){
          if(response.error == 0){
          }
        });
      deferred.resolve('Success') ;
      return deferred.promise;
    }

您可以在这里遵循promise链模式,在promise对象上使用.then进行链接。

无需使用$q创建额外开销的promise,因为$http方法在启动ajax时返回promise对象。

代码

$scope.function1 = function() {
  return $http.post(api1, data1)
    .then(function(d) {
    var response = d.data;
    if (response.error == 0) {
      console.log(response.result);
      $scope.result1 = response.result;
    }
    return response;
  });
};
$scope.function1().then(function(data) {
  $scope.function2();
}, function(error) {
});

不能将$http请求转换为"同步"请求。这不是"延期"的作用。Deferred是一种将不具有promise功能的函数转换为具有promise能力的函数的方法。$http函数返回promise对象,因此不需要使用deferred。

$http.post(api, data1).then(function (response) {
  $scope.result1 = response.data.result;
  // return is important here
  // so that you can keep chaining with .then
  return $http.post(api2, response.data.result);
}).then(function (response) {
  // here you have response from api2
  $scope.result2 = response.data.result;
  console.log(response.data);
}).catch(function (error) {
  // here you can handle errors
  // from either api calls
  // second api call won't be made if the first one fails
  console.log(error);
});