Как передать переменную из $ http success в другой запрос $ http в Angularjs? - PullRequest
0 голосов
/ 20 июня 2019

Я не могу получить доступ к выходной переменной из моего первого http-запроса get, мне нужны эти данные для другого http-запроса.

Нет.

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

}

Мне нужна область $.osChild будет присутствовать в моем запросе на пост http.

Ответы [ 2 ]

3 голосов
/ 20 июня 2019

Просто соедините два XHR:

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

Метод .then возвращает новое обещание , которое разрешается или отклоняется с помощью возвращаемого значения successCallback, errorCallback (если только это значение не является обещанием, в этом случае оно разрешается со значением, которое разрешено в этом обещании, используя объединение обещаний .

Для получения дополнительной информации см.

0 голосов
/ 20 июня 2019

первый вызов GET является асинхронным, поэтому $scope.osChild изначально устанавливает null.поэтому советуем использовать Promises https://ng2.codecraft.tv/es6-typescript/promises/

$scope.getOSChild = function() {
  var deferred = $q.defer();
  $http.get(url + 'getOSchild')
    .then(function onSuccess(response) {
      $scope.osChild = response.data;
      deferred.resolve(response.data);
  }).catch(function onError(response) {
      console.log(response.data);
      console.log(response.status);
      deferred.reject(response.status);
    });
  return deferred.promise;
};

$scope.submit = function(x) {

  $scope.getOSChild().then(function (osChild) {
    $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: osChild
      }),
      header: {
        'Content-Type': 'application/json'
      },
    }).then(function onSuccess(response) {
      console.log(response);
    }, function onError(response, status) {});

  });

};
...