AngularJS return 填充 posts 数组后的工厂
AngularJS return the factory after posts array was populated
我有以下 AngularJS 工厂,我在其中使用我的 API 数据:
.factory('posts', function posts($http) {
var posts = [];
$http.get('/api').success(function(data) {
posts = data;
});
/* === return this after $http is done === */
return {
get: function(offset, limit) {
return posts.slice(offset, offset + limit);
},
total: function() {
return posts.length;
}
}
});
我的问题是我需要 return get() 在填充 posts 数组后,当 $http
请求完成时。
有人可以向我解释如何实现这一目标吗?
Return $http.get()
完成时的工厂方法。
你必须return承诺。
.factory('posts', function posts($http,$q) {
var posts = [];
/* === return this after $http is done === */
return {
get: function(offset, limit) {
var deferred = $q.defer();
if(posts.length==0){
$http.get('/api').success(function(data) {
posts = data;
deferred.resolve(posts.slice(offset, offset + limit));
});
} else {
deferred.resolve(posts.slice(offset, offset + limit));
}
return deferred.promise;
},
total: function() {
return posts.length;
}
}
});
我有以下 AngularJS 工厂,我在其中使用我的 API 数据:
.factory('posts', function posts($http) {
var posts = [];
$http.get('/api').success(function(data) {
posts = data;
});
/* === return this after $http is done === */
return {
get: function(offset, limit) {
return posts.slice(offset, offset + limit);
},
total: function() {
return posts.length;
}
}
});
我的问题是我需要 return get() 在填充 posts 数组后,当 $http
请求完成时。
有人可以向我解释如何实现这一目标吗?
Return $http.get()
完成时的工厂方法。
你必须return承诺。
.factory('posts', function posts($http,$q) {
var posts = [];
/* === return this after $http is done === */
return {
get: function(offset, limit) {
var deferred = $q.defer();
if(posts.length==0){
$http.get('/api').success(function(data) {
posts = data;
deferred.resolve(posts.slice(offset, offset + limit));
});
} else {
deferred.resolve(posts.slice(offset, offset + limit));
}
return deferred.promise;
},
total: function() {
return posts.length;
}
}
});