Search code examples
angularjsangularjs-serviceangularjs-factory

AngularJS : call promise method in factory


I have a angular factory in the following way , but when i try to call getDepositAccountDetailsService i am getting the following error:

TypeError: this.getDepositAccountDetails.getDepositAccountDetailsService is not a function

How to call the promise inside factory.

  tellApp.factory('TabsFactory', function($resource){
    var activetabs = {};
    activetabs.getDepositAccountDetails = function(){
            $resource('XXXXXXX/:number', {}, {      
              getDepositAccountDetailsService: { method: 'GET', isArray: false}
            });
        }
    activetabs.setAccountInfo = function(accountnumber, result) {       
        var accountinit = {               
                accountInfo:[]                  
            };

      if(result.code == "s") {       
         this.getDepositAccountDetails.getDepositAccountDetailsService({number : accountnumber}).$promise.then(function(response){
                 return accountinit.accountInfo = response;

        }, function(error) {

        });
      }     
    }
    return activetabs;
  });

controller

$scope.accountInfo = TabsFactory.setAccountInfo(accountnumber, $scope.result);

Solution

  • I think you missed couple of things in your code,

    1. return $resource from service method getDepositAccountDetails
    2. this.getDepositAccountDetails should be activetabs.getDepositAccountDetails() because you created a var for factory context.

    Factory

    tellApp.factory('TabsFactory', function($resource) {
        var activetabs = {};
        activetabs.getDepositAccountDetails = function() {
            return $resource('XXXXXXX/:number', {}, {
                getDepositAccountDetailsService: {
                    method: 'GET',
                    isArray: false
                }
            });
        }
        activetabs.setAccountInfo = function(accountnumber, result) {
            var accountinit = {
                accountInfo: []
            };
    
            if (result.code == "s") {
                activetabs.getDepositAccountDetails().getDepositAccountDetailsService({
                    number: accountnumber
                }).$promise.then(function(response) {
                    return accountinit.accountInfo = response;
    
                }, function(error) {
    
                });
            }
        }
        return activetabs;
    });