假设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