angular js http get

angular js http get

本文关键字:get http js angular      更新时间:2023-09-26

我对angularJS不太熟悉,并且在尝试使用http.get()时遇到麻烦。我正在完成 QR 扫描,然后从 QR 码收到的文本将被放入我的 url 中。我收到的问题是 http.get() 在扫描完成之前正在执行。因此返回"错误"。我怎样才能做到这一点,以便 http.get(url) 仅在$scope后执行。QRScan() 函数完成。

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

$http.get() 是异步

你可以这样写:

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

有几种方法可以做到这一点,以上在以下角度文档中的"快捷方式方法"下:https://docs.angularjs.org/api/ng/service/$http