我的一个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()返回时没有得到解决.
我怎么能绕过这个?
让我们说通过异步方式从applicationsService返回的数据是:
var data = [ { "PreAlertInventory": "5.000000","SharesInInventory": "3.000000","TotalSharesSold": "2.000000" }
和applicationsService工厂返回承诺:
.factory('applicationsService',['$resource','$q',$q) { var data = [ { "PreAlertInventory": "5.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',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