等待功能完成设置为rootScope angularjs

时间:2015-10-12 15:21:38

标签: angularjs

我有异步功能的问题,我试图使用rootScope调用服务并获取数据,我有控制器调用服务并调用rootScope。但在帐户服务完成之前,rootScope首先运行,并表示未定义。

angular.module('account', ['ionic'])
.controller('accountControl', ['$rootScope', 'accountService', function ($rootScope, accountService) {
  var cusId = 1;

  accountService.getAccountList(cusId); //void function with new object and set into rootScope.

  //when I do console.log, it said undefined
  console.log($rootScope.customerAccount);
});

这是我的帐户服务

angular.module('account.service', ['ionic'])
.factory('accountService', ['$rootScope','commonService','CustomerAccount', function($rootScope,commonService,CustomerAccount) {
var factory = {};

factory.getAccountList = function (cusId) {
    var accountList = [];
    var body = {
        "cusId": cusId;
    }
    commonService.invoke(url, "getAccountsByCustomer", body, onsuccess, onfailed, null);
    function onsuccess(data, options) {
        var getResponseBody = data;
        for (var i = 0; i < getResponseBody.length; i++) {
            accountList.push({
                //mapping accountList
            });
        }
        $rootScope.customerAccount = new CustomerAccount(accountList); //new customer model and set to rootScope
    }
    function onfailed(data, options, errMsg) {
        //function failed
    }
}
return factory;
}]);

和这样的模型帐户

angular.module('pocket.customer.account',['ionic'])
.factory('CustomerAccount', function () {

  function CustomerAccount(accounts) {
      this.credits = [];
      this.deposits = [];
      for(var i in accounts) {
          if(accounts[i].key == "CREC") {
              this.credits.push(mapAccount(accounts[i]));
          }else if(accounts[i].key == "CDEP") {
              this.deposits.push(mapAccount(accounts[i]));
          }
      }
      this.credits = this.credits.length != 0 ? this.credits.sort(sort_by('product', false, function(a){return a.toUpperCase()})) : "";
      this.deposits = this.deposits.length != 0 ? this.deposits.sort(sort_by('product', false, function(a){return a.toUpperCase()})) : "";
  }

  function mapAccount(account) {
    return {
       "key": account.key,
         "value":account.value,
         "product":account.product,
    };
  }

  CustomerAccount.prototype.getCredits = function () {
      return this.credits;
  };

  CustomerAccount.prototype.getLoans = function () {
      return this.loans;
  };

  CustomerAccount.prototype.getDeposits = function () {
      return this.deposits;
  };

  CustomerAccount.create = function (accounts) {
      return new CustomerAccount(accounts);
  };

  return CustomerAccount;
});

如何在accountService之后运行console.log并设置为rootScope完成? 谢谢,

1 个答案:

答案 0 :(得分:2)

你的getAccountList也应该返回一个Promise,而不是做某事而不返回任何东西。这样,您可以使用

访问它
accountService.getAccountList(cusId).then(function(customerAccount) {
     $rootScope.customerAccount = customerAccount;
     console.log('received', customerAccount);
};