简体   繁体   English

如何链接来自不同控制器/位置的AngularJS Promise?

[英]How to chain AngularJS promises coming from different controllers / places?

So this is a bit complex, but I'll try to get into it, the best I can. 所以这有点复杂,但是我会尽力而为。 In my config.js , I have: 在我的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();
    }
  });
}]);

which basically checks to see if a user is logged in. If he is, we find out which user he belongs to with the CompanyService : 基本上检查用户是否已登录。如果是,我们通过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;
      }
    });
  };
}]);

Later on in my code, I have a call that relies on the singleton CompanyService to do an API call: 稍后在我的代码中,我有一个依赖于singleton 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);
      }
    });
  }

if I refresh the page, however, sometimes this call gets executed before we've put data in the CompanyService singleton. 但是,如果刷新页面,有时会在将数据放入CompanyService单例之前执行此调用。 How can I use promises to make sure that the LocationService doesn't happen until after we have data in the CompanyService singleton? 我如何使用Promise确保在CompanyService单例中有数据之后才发生LocationService

One way to do this is without changing your existing code too much would be to create a promise that is fulfilled when CompanyService has data. 一种方法是不对现有代码进行太多更改就可以创建一个CompanyService拥有数据时可以兑现的承诺。 Note that this code doesn't deal with errors so that still has to be added... 请注意,此代码不处理错误,因此仍然必须添加...

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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