Search code examples
javascriptangularjspromiseangular-promiseangular-resource

angular controller is executing before factory complete


I have moved some common code to factory. but the controller is executing before factory get loaded. In this case i am getting the blank response(zero results)

can anyone suggest the best solution.

here is my angular factory,

app.factory('TabsFactory', function($resource){
    var activetabs = {};            
    activetabs.getDepositAccountDetails = function() {
        return $resource('xxxx/:number', {}, {
            getDepositAccountDetailsService: {
                method: 'GET',
                isArray: false
            }
        });
    }
    activetabs.getAccountInfo = function(){
        return accountinit.accountInfo;
    }
    activetabs.setAccountInfo = function(accountnumber, result) {
         var accountinit = {
                accountInfo: []
            }
        if (result.code == "v") {           
            activetabs.getDepositAccountDetails().getDepositAccountDetailsService({
                number: accountnumber
            }).$promise.then(function(response) {
               accountinit.accountInfo = response; 
              //here i am getting the JSON response
            }, function(error) {

            });
        }
        return accountinit;
    }
    return activetabs;
  });

controller,

TabsFactory.setAccountInfo(accountnumber, $scope.accountInfo);    
$scope.accountInfo = TabsFactory.getAccountInfo();
alert(JSON.stringify($scope.accountInfo));

Solution

  • You should use chain promise to update scope variable, because your accountInfo variable is updated inside $resource promise.

    Code

    TabsFactory.setAccountInfo(accountnumber, $scope.accountInfo).then(function(data){
      $scope.accountInfo = TabsFactory.getAccountInfo();
      alert(JSON.stringify($scope.accountInfo));
    });
    

    Update

    Service method should return promise inorder to continue promise chain

    activetabs.setAccountInfo = function(accountnumber, result) {
         var accountinit = {
                accountInfo: []
            }
        if (result.code == "v") {
            //added return below      
            return activetabs.getDepositAccountDetails().getDepositAccountDetailsService({
                number: accountnumber
            }).$promise.then(function(response) {
               accountinit.accountInfo = response; 
               return accountinit.accountInfo;
              //here i am getting the JSON response
            }, function(error) {
    
            });
        }
        return accountinit;
    }