繁体   English   中英

$ http获取请求未及时在angularjs / ionic中完成

[英]$http get request not finishing in time in angularjs/ionic

我正在尝试用值而不是未定义的值填充选项,但是似乎在选择框完成加载后一直获取值。

有几项,但都没有定义。

HTML:

<label for="to">Destination:
    <select id="to" name="to" ng-model="toSelected" data-ng-options="stop.stop_id as stop.name for stop in stops">
      <option value="">Choose a Destination</option>
    </select>
  </label>

AngularJS工厂:

 .factory('DataFactory', ['$http', function ($http) {


// Might use a resource here that returns a JSON array
return {

  getAllStops: function () {
    return $http({
      method: 'GET',
      url: 'https://myAPIURL.com/api',
      headers: {
        "Accept": "application/json",
        "X-Mashape-Key": "KEYKEYKEYKEYKEYKEYKEYKEYKEYKEYKEY"
      }
    }).then(function (res) {
      return res;
    })
  },
      getAllRoutes: function () {
      return someresult similar to the above function;
  // more functions. 
  }

AngularJS控制器:

  .controller('MainCtrl', ['$scope', '$http', '_', 'DataFactory', function ($scope, $http, _, DataFactory) {

$scope.fromSelected = "";
$scope.toSelected = "";

DataFactory.getAllStops().then(function successCallback(res) {
  console.log(res);
  $scope.stops = res.data;

}, function errorCallback(err) {
  console.log("error: ");
  console.log(err);
});

$scope.changed = function (location, destination) {
console.log($scope.stops);
  $scope.possibleRoutes = DataFactory.getPossibleRoutes(location, destination);

考虑使用占位符数据初始化$scope.stops (即$scope.stops = [{stop_id: false, name: 'Loading'}]

或者,可以在数据加载完成后使用ng-if加载选择框。

例如

<div class="input" ng-if="stops"> 
  <label for="to">Destination:
    <select id="to" name="to" ng-model="toSelected" data-ng-options="stop.stop_id as stop.name for stop in stops">
       <option value="">Choose a Destination</option>
    </select>
  </label>
</div>

在控制器中,什么都没有改变。 假设您没有初始化$ scope.stops

DataFactory.getAllStops().then(function successCallback(res) {
  console.log(res);
  $scope.stops = res.data;
}, function errorCallback(err) {
  console.log("error: ");
  console.log(err);
  // TODO: Gracefully degrade
});

另一个选择是在$ scope.stops未定义时显示加载状态时执行上述操作。 这将与上面类似。

您的工厂没有按照工厂的预期兑现承诺。 按照以下步骤从工厂中删除然后“然后”以返回承诺或http请求:

 .factory('DataFactory', ['$http', function ($http) {


// Might use a resource here that returns a JSON array
return {

  getAllStops: function () {
    return $http({
      method: 'GET',
      url: 'https://myAPIURL.com/api',
      headers: {
        "Accept": "application/json",
        "X-Mashape-Key": "KEYKEYKEYKEYKEYKEYKEYKEYKEYKEYKEY"
      }
    })
  },
      getAllRoutes: function () {
      return someresult similar to the above function;
  // more functions. 
  }

一旦做出更改,控制器就会正确处理承诺,并假设您已收到响应。

另外,请验证实际响应中是否包含“ stop_id”。 与... stopID之类的相反。 如果存在stopID,但您要拉出stop.stop_id,它将显示为undefined。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM