firstChild
firstChild

Reputation: 356

How to call angular factory after another is finished?

How to call another angular factory after first factory http call is finished?

First factory:

app.factory('personService', function ($http,$rootScope) {    
  return {
    getPerson: function () {
      //return the promise directly.
      return $http.get('http://localhost:8080/emobile/api/rest/confperson/1/1').then(function (result) {
        //resolve the promise as the data
        $rootScope.userLanguage = result.data.person.languageAbbrevation;
        return result.data;
      });
    }
  }
});

Second factory which needs to be called after first is finished:

app.factory('TranslateData', function ($http,$rootScope) {

  return {
    getTranslation: function () {
      //return the promise directly.
      return $http.get('http://localhost:8080/emobile/api/rest/gettranslations/1/1/' + $rootScope.userLanguage).then(function (result) {
        //resolve the promise as the data
        return result.data;
      });
    }
  }
});

Upvotes: 0

Views: 577

Answers (2)

New Dev
New Dev

Reputation: 49590

You are correctly returning a promise (this is the result of $http) from both of those methods. All you need to do now is chain them.

personService.getPerson()
  .then(function(personResult){
     return TranslateData.getTranslation();
  })
  .then(function(translationResult){
     // do something after translation
  });

Here's a plunker with $timeout (which also returns a promise) to illustrate.

And this is the documentation of $q about chaining promises, and kriskowal/q's - which Angular's $q was inspired by.

Upvotes: 2

ŁukaszBachman
ŁukaszBachman

Reputation: 33735

What you are after is usually referred to as "chaining promises".

I wouldn't usually recommend that, as this leads to a code which:

  • is hard to maintain (you couple two services together)
  • not efficient - you could run those calls in parallel and therefore obtain the results from server faster
  • looks ugly :-)

Based on my experience, usually the best and most efficient way is to prepare all the needed data on the server (therefore have one HTTP calls instead of two). If that's not possible, then I prefer to create a service which caches promises to gettranslations resource and favor that whenever appropriate.

Hard to tell you more without look into the full code, but that's my first impression. If you really want to do that, though, then you can always call:

personService.getPerson().success(funciton() {

  // When first call finished, then start the 2nd one

  TranslateData.getTranslation().success(function(){

     // Both calls have finished at this point.

  });

});

Upvotes: 0

Related Questions