【问题标题】:angular js http get角度 js http 获取
【发布时间】:2016-03-20 02:15:07
【问题描述】:

我对 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;
};

【问题讨论】:

  • 这个 $scope.QRscan() 是返回一个承诺,还是接受一个回调函数? node.js 是非阻塞的,意味着不保证 $scope.QRscan() 会在 var params = "?number=" + $scope.QRText; 之前完成您必须使用回调或等待承诺解决

标签: javascript angularjs get ionic-framework


【解决方案1】:

$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

【讨论】:

  • 谢谢!那和文档帮助我解决了问题。
猜你喜欢
  • 1970-01-01
  • 2018-05-31
  • 2013-09-01
  • 2015-04-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-04-26
  • 1970-01-01
相关资源
最近更新 更多