angularjs return another promise in $q.all

546 views Asked by At

in my angularjs/ionic application I'm getting data from a sqlite database and want to get data from a web service which depends on the values of the database variables. I thought this might be possible with:

.factory('WebSrvs', function($http,DatabaseSrvs) {

var getData = function() {

var promiseReceiverUrl = DatabaseSrvs.getLocalValue('value1');
var promiseVehicleId = DatabaseSrvs.getLocalValue('value2');

$q.all([promiseReceiverUrl,promiseVehicleId]).then(function(results) {

  if(results[0].rows.length > 0 && results[1].rows.length > 0) {

    var v1 = results[0].rows.item(0).Value;
    var v2 = results[1].rows.item(0).Value;

    var req = {
      method: 'POST',
      url: v1,
      headers: {
        'Content-Type': 'application/json; charset=utf-8'
      },
      data: {
        value: v2
      },
      timeout: 10000,
      crossDomain: true
    };

    return $http(req);
  }
});
}
}

But if do it this way and call it with var promise1 = WebSrvs.getData(); I don't get anything back and the app runs in a reloading queue which never ends. What am I doing wrong?

2

There are 2 answers

2
wjohnsto On BEST ANSWER

To add to my comments:

.factory('WebSrvs', function($http,DatabaseSrvs) {

    var getData = function() {

        var promiseReceiverUrl = DatabaseSrvs.getLocalValue('value1');
        var promiseVehicleId = DatabaseSrvs.getLocalValue('value2');

        return $q.all([promiseReceiverUrl,promiseVehicleId]).then(function(results) {

          if(results[0].rows.length > 0 && results[1].rows.length > 0) {

            var v1 = results[0].rows.item(0).Value;
            var v2 = results[1].rows.item(0).Value;

            var req = {
              method: 'POST',
              url: v1,
              headers: {
                'Content-Type': 'application/json; charset=utf-8'
              },
              data: {
                value: v2
              },
              timeout: 10000,
              crossDomain: true
            };

            return $http(req);
          }
        });
    }

    return {
        getData: getData
    };
}
0
ShankarSangoli On

In your factory implementation you need to first return getData function. Also inside getData function you have to return $q.all.

.factory('WebSrvs', function($http,DatabaseSrvs) {

  var getData = function() {

   var promiseReceiverUrl = DatabaseSrvs.getLocalValue('value1');
   var promiseVehicleId = DatabaseSrvs.getLocalValue('value2');

    return $q.all([promiseReceiverUrl,promiseVehicleId]).then(function(results) {
     ...
     ...
    });
  }
  return {
   getData: getData
  }
}