如何链接来自不同控制器/场所的AngularJS承诺?

时间:2014-02-19 03:29:32

标签: javascript angularjs promise q

所以这有点复杂,但我会尝试进入它,我能做到最好。在我的config.js中,我有:

.run(['$rootScope', '$location', 'UserService', 'CompanyService', function($rootScope, $location, UserService, CompanyService) {
  $rootScope.globals = {};

  $rootScope.$on('login', function(event, data) {
    $rootScope.api_key = data.api_key;
    CompanyService.get(data.user.company_id);
  });

  UserService.checkAuth().then(function(response) {
    if(response.data.user) {
      // Logged in user
      $rootScope.$broadcast('login', response.data);
    } else {
      UserService.logout();
    }
  });
}]);

基本上检查用户是否已登录。如果是,我们通过CompanyService找出他所属的用户:

angular.module('mean').service('CompanyService', ['$http', '$rootScope', function($http, $rootScope) {
  var company = this;
  company.company_data = {}

  company.getCompany = function() {
    return company.company_data;
  }

  company.get = function (company_id) {
    return $http({
      url: '/api/v1/company/' + company_id,
      method: 'GET',
      headers: {
        api_key: $rootScope.api_key
      }
    }).success(function(response) {
      if(response.status === 'ok') {
        company.company_data = response.company;
      }
    });
  };
}]);

稍后在我的代码中,我有一个依赖单例CompanyService进行API调用的调用:

  $scope.index = function() {
    LocationService.get(CompanyService.getCompany()._id, $routeParams.location_parent_id).then(function(response) {
      if(response.data.status === 'ok') {
        $scope.locations = $scope.locations.concat(response.data.locations);
      }
    });
  }

但是,如果我刷新页面,有时在我们将数据放入CompanyService单例之前执行此调用。我怎样才能使用promises来确保LocationServiceCompanyService单例中有数据之后才会发生?

1 个答案:

答案 0 :(得分:1)

执行此操作的一种方法是在不更改现有代码的情况下过多地创建在CompanyService包含数据时履行的承诺。请注意,此代码不处理错误,因此仍然需要添加...

angular.module('mean').service('CompanyService', 
        ['$http', '$rootScope', '$q', function ($http, $rootScope, $q) {
    var company = this;
    company.company_data = {}

    var initializedDeferred = $q.defer;
    company.initialized = initializedDeferred.promise;

    company.getCompany = function () {
        return company.company_data;
    }

    company.get = function (company_id) {
        return $http({
            url: '/api/v1/company/' + company_id,
            method: 'GET',
            headers: {
                api_key: $rootScope.api_key
            }
        }).success(function (response) {
            if (response.status === 'ok') {
                company.company_data = response.company;
                initializedDeferred.resolve(); // reject promise on error?
            }
        });
    };
}]);

$scope.index = function () {
    CompanyService.initialized.then(function () {
        LocationService.get(CompanyService.getCompany()._id,
            $routeParams.location_parent_id).then(function (response) {
            if (response.data.status === 'ok') {
                $scope.locations = $scope.locations
                      .concat(response.data.locations);
            }
        });
    });
}