Nick R. Nick R. - 3 months ago 8
Ajax Question

$http get request not finishing in time in angularjs/ionic

I'm trying to fill options with values instead of undefined, but seems to keep getting the values after the select box has finished loading.

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:

.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:

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

Answer

Your factory isn't returning a promise as expected in your factory. Remove then 'then' from the factory as follow to return a promise, or the http request.:

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

The controller is handling the promise correctly once that change is made assuming you're getting a response.

Also, verify that "stop_id" is on the actual response. As opposed to... stopID or something. if stopID is there, but you're pulling stop.stop_id, it would show as undefined.