AngularJS : 在工厂中调用 promise 方法

AngularJS : call promise method in factory

我按以下方式有一个 angular 工厂,但是当我尝试调用 getDepositAccountDetailsS​​ervice 时,出现以下错误:

TypeError: this.getDepositAccountDetails.getDepositAccountDetailsService is not a function

如何在工厂中调用promise。

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

控制器

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

我认为您在代码中遗漏了几件事,

  1. return 来自服务方法的 $resource getDepositAccountDetails
  2. this.getDepositAccountDetails 应该是 activetabs.getDepositAccountDetails() 因为您为工厂上下文创建了一个变量。

工厂

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