Search code examples
angularjsangular-promiseangularjs-http

How to "pass variable from $http success to another $http request" in Angularjs?


I can't access the output variable from my 1st http get request, i need this data for another http Post request.

None.

$scope.submit = function(x) {

  $http({
    method: "GET",
    url: url + 'getOSchild',
    params: { ncard: x }
  }).then(function success(response) {
    $scope.osChild = response.data;
    console.log($scope.osChild) // this has an output
  }, function error(response, status) {
    console.log(response)
    console.log(status)
  });


  $http({
    method: "POST",
    url: url + 'printOS',
    data: JSON.stringify({
      CARD_NAME: data_cname,
      C_DATE: data_date,
      C_NUMATCARD: data_ncard,
      C_DISTMEANS: data_means,
      C_TIME: data_time,
      cData: $scope.osChild //this is null
    }),
    header: {
      'Content-Type': 'application/json'
    },
  }).then(function success(response) {
    console.log(response)
  }, function error(response, status) {});

}

I need the $scope.osChild to be present in my http post request.


Solution

  • Simply chain the two XHRs:

    function getOSChild (x) {
        return $http({
            method: "GET",
            url: url+'getOSchild',
            params: {ncard: x}
        }).then(function success(response) {
            $scope.osChild = response.data;
            console.log($scope.osChild); // this has an output
            return response.data;
         },function error(response) {
            console.log(response)
            console.log(response.status);
            throw response;
        });
    }
    
    $scope.submit = function(x) {  
        getOSChild(x).then(function(osChild) {
            $http({
                method: "POST",
                url: url+'printOS',
                data:{ CARD_NAME: data_cname, 
                          C_DATE: data_date,
                     C_NUMATCARD: data_ncard, 
                     C_DISTMEANS: data_means,
                          C_TIME: data_time, 
                           cData: osChild //chained
    
                }
            }).then(function success(response) {
                  console.log(response)
            });
        });
    };
    

    The .then method returns a new promise which is resolved or rejected via the return value of the successCallback, errorCallback (unless that value is a promise, in which case it is resolved with the value which is resolved in that promise using promise chaining.

    For more information, see