sarahholden
sarahholden

Reputation: 650

Angular Factory - Return two sets of data

I have a factory in Angular and I want to make two API calls and return the data to my controller. I've been having a little bit of trouble returning both sets of data - especially with the .catch. I'm an Angular n00b so I'm getting a little thrown off with the async promises. I've tried using $q.all but it doesn't seem to be working with the catch. Let me know if you need any more info!!

  .factory('initializeCoreModels', ['$q','userModel', 'redirect', 'countryList',
                      function($q, userModel, redirect, countryList){
    return function(){
      return countryList.getAll()
      return userModel.getModel()
        .catch(function(error){
          if (error.status){
            return redirect.hrefUrl('/');
          }
          return $q.reject(error);
        });


    };

Upvotes: 0

Views: 401

Answers (1)

Brian Noah
Brian Noah

Reputation: 2972

You can only have one return. so you need to return an object with both promises:

app.factory('initializeCoreModels',['$q','userModel', 'redirect', 'countryList', function ($q, userModel, redirect, countryList) {
    var returnObj = {
      countryList: countryList.getAll()
      userModel: userModel.getModel()
    };
    returnObj.userModel.catch(function(error){
      if (error.status){
        return redirect.hrefUrl('/');
      }
      return $q.reject(error);
    });
    return returnObj;
}]);

This still checks your userModel promise, but you can now access your promise with the .catch()

Upvotes: 1

Related Questions