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

时间:2016-08-25 23:59:32

标签: javascript angularjs ajax http ionic-framework

我试图用值而不是未定义填充选项,但似乎在选择框加载完毕后继续获取值。

Several items, but all undefined.

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

2 个答案:

答案 0 :(得分:2)

考虑使用占位符数据初始化$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。这将与上述类似。

答案 1 :(得分:2)

您的工厂没有按照您工厂的预期退回承诺。然后从工厂中删除'then',如下所示返回一个promise或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_id,它将显示为未定义。