7

我的 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() 返回时,此调用可能尚未解决。

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

4

3 回答 3

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

于 2013-10-25T10:06:24.030 回答
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;
     }
   }
于 2013-10-25T09:06:21.283 回答
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: ...
});
于 2016-05-05T21:19:28.743 回答