0

I am not too familiar with angularJS and am having trouble trying to use http.get(). I am completing a QR scan and the text that is received from the QR code will then be placed into my url. The problem that I am receiving is that the http.get() is executing before the scan is being completed. Therefore returning "Error". How can I make this so that the http.get(url) is executed only after the $scope.QRScan() function is completed.

  $scope.QRscan(); /// Want to finish first

  var params = "?number=" + $scope.QRText;
  params += "&action=ci";

  var url = "http://test/test.php" + params;

  var promise = $http.get(url);

  promise.then(
    function(payload) {
      var r = payload.data;

      if (r.status.toString() == '1') {
        var alertPopup = $ionicPopup.alert({
          title: ' successful ',
        });
      } else {
        var alertPopup = $ionicPopup.alert({
          title: 'Error',
        });

      };
    });

QRScan()

  $scope.QRscan = function () {
  $cordovaBarcodeScanner.scan().then(function (qrData) {
  }, function (error) {
    var alertPopup = $ionicPopup.alert({
      title: 'There was an error scanning the QR code.',
    });
  });
     $scope.QRText = qrData.text;
};
1
  • does this $scope.QRscan() return a promise, or accept a callback function? node.js is non-blocking, means no guarantee $scope.QRscan() will finish before var params = "?number=" + $scope.QRText; You have to use either callback or wait for promise resolving Commented Mar 20, 2016 at 2:22

1 Answer 1

0

$http.get() is asynchronous

you can write it like this:

function getData() {
  return $http.get(url)
    .then(function(data) {
    // this is where we can manipulate your data
    // set to $scope object/whatever
    // because its async, we need to use a promise (or callback) to wait for
    // the response from your get request
  })
  .catch(function(err) {
    // if err, console.log(err)
  })
}

There are a couple ways to do this, the above is under 'Shortcut Methods' in the following angular docs: https://docs.angularjs.org/api/ng/service/$http

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! That and the documentation helped my problem.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.