0

I have a state which resolves as :

resolve: {
              accounts: function(utils) {
                return utils.getAccounts();
              },
              data: function(utils) {
                return utils.getData();
              },
              termsData: function(utils) {
                return utils.getTerms();
              }
            }

I need to make sure that data and termsData are called only after accounts is returned in angular resolve.

getAccounts function looke like :

 function getAccounts() {
            var deferred = $q.defer();
            Restangular.setBaseUrl(baseUrl());
            var accountsService = Restangular.all(accountsUrl);
            accountsService.post({headers}).then(function(data) {
              deferred.resolve(data);
            }, function(ex) {
              deferred.reject(ex);
            });
            return deferred.promise;
          }
Pankaj Parkar
  • 134,766
  • 23
  • 234
  • 299
theConstructor
  • 109
  • 2
  • 13

3 Answers3

2

You could add accounts as a dependency the same way like I suppose you do in controller:

resolve: {
          accounts: function(utils) {
            return utils.getAccounts();
          },
          data: ['accounts', 'utils', function(accounts, utils) {
              accounts.then(function(data){
                 return utils.getData();
              }, function(data){
                 return $q.reject();
              });
          }]
        }
}
artgladun
  • 534
  • 5
  • 9
0

You could do call other two once getAccounts function promise get resolved and then do return data with getData & getTerms promise with $q.all.

resolve: {
    accounts: function(utils, $q) {
        return utils.getAccounts().then(function(accounts){
            return $q.all([accounts, utils.getData(), utils.getTerms()])
        });
    }
}

Controller

app.controller('mainCtrl', function($q, $scope, accounts){
    console.log("accounts", accounts[0])
    console.log("getData Response", accounts[1])
    console.log("getTerms Response", accounts[2])
})
Pankaj Parkar
  • 134,766
  • 23
  • 234
  • 299
-1

Assuming you need to get all your data asynchronously you can simply restructure your code to take advantage of the promise pattern.

var getAccounts = function(...) {
  return new Promise(resolve, reject) {
    ... do something and resolve or reject
  };
};

var getTermsData = funciton= function(...) {
  return new Promise(resolve, reject) {
    ... do something and resolve or reject
  };
};

var getData = = function(...) {
  return new Promise(resolve, reject) {
    ... do something and resolve or reject
  };
};

getAccounts.then(function(accounts) {
  return getTermData();
}.then(function(termData) {
  return getData(data);
}.catch(function() {
  // something went wrong!
}
Amonn
  • 84
  • 6