在加载资源之前等待承诺解决

时间:2013-10-25 08:57:35

标签: angularjs promise

我的一个AngularJS控制器包含以下行:

api.tickets.query()

api模块包含:

angular.module('myapp.api', [
  'ngResource'
])

.factory('api', function($resource, applicationsService) {

  function fetchAppId() {
    return applicationsService.getCurrentApp();
  }

  return {
    tickets: $resource('tickets', {
      applicationId: fetchAppId
    }),
    ...
  }

applicationsService.getCurrentApp()自己进行$ http调用。所以你也许可以看到问题 - 这个调用可能在fetchAppId()返回时没有得到解决。

我怎样才能解决这个问题?

3 个答案:

答案 0 :(得分:7)

让我们说通过异步方式从applicationsService返回的数据是:

 var data = [
    {
        "PreAlertInventory": "5.000000",
        "SharesInInventory": "3.000000",
        "TotalSharesSold": "2.000000"
    }

applicationsService工厂退货承诺:

.factory('applicationsService', ['$resource','$q',  function($resource, $q) {
    var data = [
    {
        "PreAlertInventory": "5.000000",
        "SharesInInventory": "3.000000",
        "TotalSharesSold": "2.000000"
    }
    ];   

       var factory = {
            getCurrentApp: function () {
                var deferred = $q.defer();   

              deferred.resolve(data);

                return deferred.promise;
            }
        }
        return factory;
}]);

我只需致电api.tickets()

$scope.data = api.tickets(); 

但我们的api服务将如下所示:

.factory('api', function($resource, applicationsService,$q, $timeout) {

  function fetchAppId() {      
      return applicationsService.getCurrentApp();
  }

  return {
 tickets: function() {
         var deferred=$q.defer();
        fetchAppId().then(function(data) { // promise callback
            $timeout(function(){         // added dummy timeout to simulate delay
                    deferred.resolve(data);    
                }, 3000);                    
        });
        return deferred.promise;
     }
   }
});   

演示 Fiddle

答案 1 :(得分:4)

你需要做的就是为自己创造一个承诺。

.factory('api', function($resource, applicationsService,$q) {

  function fetchAppId() {
    return applicationsService.getCurrentApp();
  }

  return {
    tickets: function() {
        var defer=$q.defer();
        fetchAppId().then(function(data) {
             var appId=data;
             $resource('tickets', {applicationId: appId})
                 .then(function(data) {
                      defer.resolve(data);
                 })
        }
        return defer.promise;
     }
   }

答案 2 :(得分:1)

如果您想在路线更改之前等待角度资源($resource)得到解决,那么您需要返回$promise

$routeProvider.when('/tickets', {
    resolve: {
        'tickets': function ('Ticket') {
            // do this to resolve the async call prior to controller load
            return Ticket.query().$promise;

            // this will resolve 'tickets' during/after controller load
            return Ticket.query();
        }
    },
    controller: ...
});