0

I'm using Angularjs and i have made this service with multiples functions that returns promises .

My AJAX service :

angular.module('yoApp')
    .factory('serviceAjax', function serviceAjax($http) {
      return{
      
        configDataSets:function(path){

          return $http.get(path);

        },
        fileList: function(site_url,dataSet,varName,region,date){
          return $http.get(site_url + "mwf/" + dataSet + "/" +varName + "/" + region + "/" + date + "/filelist/");
        },
        config: function(site_url,dataSet){
          return $http.get(site_url + "mwf/" + dataSet + "/config/");
        },

      }});

Controller code

I have already done something like this but as i may have more requests chained i think that's not the best way to do this :

serviceAjax.config(site_url,$scope.dataset).then function(data){
          $scope.config=data.data;
serviceAjax.configDataSets("images/configDatasets.json").then(function(data){

          $scope.configDatasets = data.data;
 
});
});

What i want to do is first Call in my controller config and then wait for it to finish then call configDataSets . what's the best way to do it, i have tried to look at $q and differed but i can't seem to figure out how to do it. Any help would be great!

1
  • see my answer - you can "chain" the .then calls without nesting them Commented Jan 19, 2016 at 11:15

1 Answer 1

1

Just use the .then method exposed by the promise:

serviceAjax.config(function(response) {
     // use response.data from first call
     ...
}).then(function() {
     return serviceAjax.configDataSets("images/configDatasets.json");
}).then(function(response) {
     // use response.data from second call
     ...
});

Also, consider using $resource instead of $http if your HTTP service follows typical RESTful usage.

Sign up to request clarification or add additional context in comments.

3 Comments

The first call is working but the second one i got an undefined for the response parameter, and i tried reversing the order and each call works for the first time but the second one i got an undefined , my code serviceAjax.config(site_url,"all").then(function(data){ console.log(data); }).then(serviceAjax.configDataSets("images/configDatasets.json")).then(function(data) { console.log(data.data); });
you can't actually pass the result of serviceAjax.configDataSets("images/configDatasets.json") into .then - you have to pass a function - I'll amend my answer to show
Ah i see you need to first return the promise then use the ".then" method thank you very much !

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.