【发布时间】:2014-09-27 05:03:50
【问题描述】:
我正在尝试构建一个允许我通过一些 API 调用加载日期的服务或工厂。 大部分数据都需要重复使用,所以基本上我只想进行一次 API 调用,下次我需要该数据时,它应该返回它。
现在,每当我进行 API 调用时,在它完成之前我会进行相同的调用,我希望第二个调用等到第一个调用完成。
基本上当我这样做时:
dataService.getMenu() // Make API call
dataService.getMenu() // Wait for the first API call to be completed and return that data
// Somewhere else
dataService.getMenu() // Return data as API call was already made
我的工厂是这样的:
(function() {
var app = angular.module('dataService', []);
app.factory('dataService', ['$http', '$q', function($http, $q) {
var links = [],
jobs = [];
return {
getMenu: function() {
var deferred = $q.defer();
console.log(links);
if(links.length > 0) {
deferred.resolve(links);
} else {
$http.get('../server/api.php?ajax=true&action=getCats').success(function(data) {
links = data;
deferred.resolve(data);
})
}
return deferred.promise;
}
}
}])
})();
【问题讨论】: