[英]$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.