简体   繁体   中英

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));

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;
}

Yes, this will happen because of JavaScript executing asynchronous operations but your controller in such a way that it expects things to be synchronous operations.

When you call TabsFactory.getAccountInfo() its possible that your $resource('xxxx/:number') is still not completed and response ready for you to process!!

So, what to do? You have make use of promise . I usually have a repository (A factory with method that return promise) to handle server communications. Here is an example:

app.factory('accountRepository', ["$http","$q",function($http,$q){

   return {
        getDepositAccountDetails : function(id) {
           var deferred = $q.defer();
           $http.ger('xxx').success(deferred.resolve).error(deferred.reject);
           return deferred.promise;
        }
   };
}] );

My repository will have more operations like add account, update account info etc..

my controller/service then calls these methods as follows:

accountRepository.getDepositAccountDetails(123).then(function(response) {
           // Process the response..
 }, function(error) {
           // Some error occured! handle it
 });

doing so, my code gets executed only after I get response from server and data is ready for consumption or display. Hope this helps..

Update: You might want to have a look at this to get the idea ;)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM