我有一种获取数据的服务方法。服务方法将首先检查本地存储是否存在该数据,如果存在则返回,否则它将使用$ resource从服务器获取数据并在将其存储在本地存储中后返回。从我的控制器我将调用此服务来获取数据。我的问题是,如何确保在ajax调用结束后返回数据。当我第一次得到undefined
services.factory('dataService', ['country','localStorageService',function(country,localStorageService) {
return {
getCountryList: function (){
var countryList = null;
if(localStorageService.isSupported) {
countryList = localStorageService.get("countryList");
}
if(countryList !==null){
return countryList ;
}
else{
country.query(function(response) {
countryList = response;
if(localStorageService.isSupported) {
localStorageService.set("countryList ",countryList );
}
return countryList ;
});
}
}
}
}]);
services.factory('country',['$resource','serverConfig',function($resource,serverConfig) {
return $resource(serverConfig.url+'/country');
}]);
答案 0 :(得分:0)
$ http服务可能对您有用。
它使用promise函数,这些函数根据是否收到响应或是否在尝试收集资源时发生错误而调用。
$http.post("link.php").
then(function(response) {
// called when successful
}, function(response) {
// called when not successful
});
link.php
打印的任何内容(echo,print_r,var_dump)将作为函数参数的响应返回。
请记住,您必须将$ http服务传递给控制器。
.controller("ItemController", function($scope, $http) {
我希望这会对你有所帮助。
答案 1 :(得分:0)
我已经使用$ q服务解决了它。
services.factory('dataService', ['$q','country','localStorageService',function($q,country,localStorageService) {
return {
getCountryList: function(){
var deferred = $q.defer();
var countryList = null;
if(localStorageService.isSupported) {
countryList = localStorageService.get("countryList");
}
if(countryList !==null){
deferred.resolve(countryList);
}
else{
country.query(function(response) {
countryList = response;
if(localStorageService.isSupported) {
localStorageService.set("countryList ",countryList);
}
deferred.resolve(countryList);
});
}
return deferred.promise;
}
}
}]);